可以通过引用传递std :: wfstream并且我能够正确使用write()和read()吗?

时间:2011-08-15 16:50:30

标签: c++ visual-studio unicode io pass-by-reference

我为我的项目使用了自制的错误/日志类,它也能够将自身存储/加载到文件中。为了让我在处理更多对象时更容易,我想通过引用传递一个文件流,然后使用该函数的写入/读取成员。

保存:

in.open(L"XError.err",std::ios::in | std::ios::out | std::ios::binary | std::ios::trunc);

加载:

in.open(L"XError.err",std::ios::in | std::ios::out | std::ios::binary);

保存:

unsigned int HError::SaveToBufferW(std::wfstream& file)
{
    _ErrorSaveStruct ess = {0};
    ESS.IsUNICODE = true;
    ESS.ItemCount = 9999999;
    file.write((wchar_t*)&ess,sizeof(_ErrorSaveStruct) / sizeof(wchar_t));
    return 0;
}

加载:

int HError::LoadFromBufferW(std::wfstream& file)
{
    _ErrorSaveStruct ess = {0};
    file.read((wchar_t*)&ess,sizeof(_ErrorSaveStruct) / sizeof(wchar_t));
    return 0;
}

我检查了文件,发现只写了空格。 当我读/写一个Unicode字符串时,一切正常,字符串也可以在文件中读取。

编辑:你去吧

 struct _ErrorSaveStruct
{
    unsigned int MsgSize;
    unsigned int TimeSize;
    unsigned int LastErrorSize;
    int ItemCount;
    int errState;
    bool InitMsg;
    bool IsUNICODE;
};

1 个答案:

答案 0 :(得分:0)

好的,用另一个答案以某种方式绕过我的问题:

int main()
{   
HLib::_ErrorSaveStruct Ess = {0};  // just a namespace
Ess.IsUNICODE = true;
Ess.errState = 100;
Ess.ItemCount = 9999;

wchar_t* StringTest[1] = {L"WOORD"};    // same like (wchar_t[5])

FILE* iobuf = NULL;

// create new in binary read-write mode
if (_wfopen_s(&iobuf,L"WTest.err",L"wb+")==0) 
{
        //WRITING BLOCK
    if (fwrite(&Ess,sizeof(Ess),1,iobuf) != 1)  // sizeof_ErrorSaveStruct
        std::cout << "Fail (Reading struct)";

    if (fwrite(StringTest,sizeof(wchar_t) * 5,1,iobuf) != 1) // size = 5 
        std::cout << "Fail (Reading string)";

    // reset content
    SecureZeroMemory(&Ess,sizeof(Ess));
    SecureZeroMemory(StringTest,sizeof(wchar_t)*5);

    fseek(iobuf,0,0); // rewind
    fflush(iobuf);    // flush because you switch from write to read

     /// READING BLOCK
    if (fread(&Ess,sizeof(Ess),1,iobuf) != 1)   // sizeof_ErrorSaveStruct
        std::cout << "Fail (Reading struct)";

    if (fread(StringTest,sizeof(wchar_t) * 5,1,iobuf) != 1) // size = 5 
        std::cout << "Fail (Reading string)";
    fclose(iobuf);
}

return 0;

我真的学到了关于流和文件IO的东西。考虑到其他解决方案,我也可以将单个参数(int,bool)传递给wfstream而不是整个结构。使用带有二进制标志的std :: fstream并通过write()传递一个wchar_t字符串也是可能的。无论如何,这个解决方案对我来说效果很好,我真的很高兴。