我試圖環繞FILE *類,這裏是分配失敗的FILE *類
class file_ptr
{
public:
file_ptr(const wstring& _FileN, const wstring& _OpenMode) : file_n(_FileN), omode(_OpenMode),
fptr(_wfopen(file_n.c_str(), omode.c_str()))
{
if (!fptr)
throw wstring(L"Failed to open File ") + _FileN;
}
~file_ptr()
{
fclose(fptr);
}
file_ptr& operator =(const file_ptr& other)
{
if (this != &other)
{
this->~file_ptr();
fptr = other.fptr;
file_n = other.file_n; omode = other.omode;
}
}
operator FILE*() { return fptr; }
private:
wstring file_n, omode;
FILE* fptr;
};
爲什麼wstring的?我需要Unicode支持。
現在的問題可以說是做了這樣的事情
int main() {
try {
file_ptr file1(L"text1",L"wb");
fwrite("Hello",1,5,file1);
file1 = file_ptr(L"text2",L"wb");
fwrite("Hello",1,5,file1);
} catch (const wstring& e) {
wcout << e << endl;
}
return 0;
}
什麼都不會寫在文本2
我甚至試着刪除我的任務過載後,becoz我想默認的行爲應該是一樣的,但問題仍然存在
它的工作原理,如果我使用*預期FE
int main() {
try {
FILE* file1 = _wfopen(L"text1",L"wb");
fwrite("Hello",1,5,file1);
fclose(file1);
file1 = _wfopen(L"text2",L"wb");
if (!(file1))
throw L"Can't open file";
fwrite("Hello",1,5,file1);
} catch (const wstring& e) {
wcout << e << endl;
}
return 0;
}
RAW文件
text2的正確寫入,
爲什麼要手動調用析構函數? – Brandon
你打算如何在'FILE *'上使用'WCHAR'? – stackptr
將它轉換爲char *並在字符串之前存儲大小和長度 – bluedragon