[C++]How to create your own file

Started by
6 comments, last by Zahlman 13 years, 11 months ago
I want to create my 'own' custom file format. I have a header that currently looks like this:

struct HeaderInfo
{
	unsigned int width;
	unsigned int height;
};


Currently I use this to write to the file:

FILE* f;
fopen_s(&f, "image.fun", "w+");


Now how do I write to headerInfo to the file using fputs(); This needs a char* but how can I cast HeaderInfo to a char*? I tried using static_cast but this gives an compile error: cannot convert to char*
Advertisement
Found that its better to use fwrite :P
Another question! :P

I'm using fwrite to write to a file.
When the size of this data is small its not a problem but when the size becomes too big it crashes. Any ideas why?

// If size is small like 2048fwrite(&data, sizeof(DataStruct), size, f);// If size is big like 262144 fwrite(&data, sizeof(DataStruct), size, f); // CRASH :(

what's the value of 'size' ?
If data isn't an array, you should use 1 instead of size.
The second parameter to fwrite is the size of the item to write and the third one is how many of them. The size written to the file will be sizeof(DataStruct) * size.

If you're using C++, i'd suggest to look into std::ofstream which is the C++ way of writing to files.

hope that helps
What is data declared as? for what you've written to work, it needs to be a struct containing an array of at least 262144*size bytes (Not just an array on the stack)
Quote:Original post by Boogy
Found that its better to use fwrite :P


Take care when using fwrite to write POD structs. The compiler can insert padding between elements and that padding (bytes of undetermined value) will also be written to your file.

Different compilers are at liberty to insert different amounts of padding, so if you compile your code on a different system (or with a different compiler on the same system) the generated program might not write compatible data. Of course the same applies to fread-ing into structs; if the compiled layout differs between two programs, your data format is not portable (at best) or broken (at worst).

Most compilers provide a mechanism such as a pragma to ensure that padding isn't inserted between elements (at least on x86 where alignment isn't strict).
// If size is big like 262144
fwrite(&data, sizeof(DataStruct), size, f); // CRASH :(

size actually should be count - as written fwrite would try to send size number of structures to the file. Not 262144 bytes but 262144 structures!.

the correct template for fwrite is

fwrite (&Data , sizeof(DataStructure), NumberOfStructures, FileDescriptor)
template <typename T>void write(ofstream& f, const T& t) {  f.write(reinterpret_cast<const char*>(&t), sizeof(T));}// ...std::ofstream f("image.fun", std::ios::binary);HeaderInfo h;write(f, h.width);write(f, h.height);

This topic is closed to new replies.

Advertisement