开发者

Writing to file using c and c++

When I try to write the file using C; fwrite which accepts void type as data, it is not interpreted by text editor.

struct index
开发者_如何学Go{
   index(int _x, int _y):x(_x), y(_y){}
   int x, y;
}

index i(4, 7);

FILE *stream;
fopen_s(&stream, "C:\\File.txt", "wb");
fwrite(&i, sizeof(index), 1, stream);

but when I try with C++; ofstream write in binary mode, it is readable. why doesn't it come up same as written using fwrite?


This is the way to write binary data using a stream in C++:

struct C {
    int a, b;
} c;

#include <fstream>
int main() {

    std::ofstream f("foo.txt",std::ios::binary);
    f.write((const char*)&c, sizeof c);
}

This shall save the object in the same way as fwrite would. If it doesn't for you, please post your code with streams - we'll see what's wrong.


C++'s ofstream stream insertion only does text. The difference between opening a iostream in binary vs text mode is weather or not end of line character conversion happens. If you want to write a binary format where a 32 bit int takes exactly 32 bits use the c functions in c++.

Edit on why fwrite may be the better choice:

Ostream's write method is more or less a clone of fwrite(except it is a little less useful since it only takes a byte array and length instead of fwrite's 4 params) but by sticking to fwrite there is no way to accidentally use stream insertion in one place and write in another. More less it is a safety mechanism. While you gain that margin of safety you loose a little flexibility, you can no longer make a iostream derivative that compresses output with out changing any file writing code.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜