开发者

Need explanation of reading and writing of wchar_t* to binary file

can someone explain me what is a proper way to write wchar_t* string to binary file and then read it back(using fread/fwrite)?

here is what i have (its working)

struct someStruct{
    int someint;
    wchar_t* data;
    int someint2;
}
someStruct s;
s.someint = 111;
s.data = L"blah blah .... lets say 1-1000 characters long";
s.someint2 = 222;

//writing
FILE * f = _wfopen(L"myfile",L"wb");
fwrite(&(s.someint), sizeof(int), 1, f);
fwrite(&(s.data), sizeof(wchar*), 1, f);
fwrite(&(s.someint2), sizeof(int), 1, f);
fclose(f);

//reading
FILE * f2 = _wfopen(L"myfile",L"rb");
fread(&(s2.someint), sizeof(int), 1, f2);
fread(&(s2.data), sizeof(wchar*), 1, f2);
fread(&(s2.someint2), 开发者_Go百科sizeof(int), 1, f2);
fclose(f2);

everything is working, values are properly loaded. the question is what should be the second parameter of fread and fwrite in this specific example, why is it working with e.g. 4(which is sizeof(wchar_t*)) or 20 and causing buffer overrun with 150, these values vary based on data length,

EDIT: these are what i have been using (was working last time i checked it :P 1 year ago):

wchar_t* loadStrFromFile(FILE* file) {
    int strLen;
    fread(&(strLen), sizeof(int), 1, file);
    wchar_t* result = new wchar_t[strLen];
    fread(result, strLen, sizeof(wchar_t), file);
    return result;
}

void saveStrToFile(const wchar_t*& data, FILE* file) {
    int strLen = wcslen(data)+1;
    fwrite(&strLen, sizeof(int), 1, file);
    fwrite(data, strLen, sizeof(wchar_t), file);
}


This is particularly wrong:

fwrite(&(s.data), sizeof(wchar*), 1, f);

This would only write sizeof(wchar*) = 4 or 8 bytes.

Oh yes, and you probably don't want to write a pointer. Missed that one.

If you want to write an actual string data (assuming you're on Windows):

size_t len = wcslen(s.data); //get the number of characters
fwrite(s.data, sizeof(wchar_t), len, f);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜