c++ - When writing struct to a file too many bytes are written -


I'm trying to write a simple TGA image file saver as a learning process in C ++. I am making my code based on an example TGA loader which declares a string for the header and then uses Fred (), to load the entire header at a time.

My program is not working right now, and it seems that there are two additional bytes written in the file. I printed my structured size and it is very big by two bytes (20 instead of right 18). After reading a bit, I think the problem relates to data alignment and padding (I am not very familiar with how structs are stored).

My question is, what is a good solution for this? I think I can write struct byte-by-byte, instead of using the fwrite () to write the entire structure, which I'm going now. I assumed that if the headers were used while loading, then it would also work while writing it. Was my assumption wrong?

The compiler is allowed, and repeatedly, insert the padding byte into structures, So that the fields are aligned to the appropriate memory address.

The simplest way is to give the compiler instructions to "pack" structure, which means do not include any padding byte. Although this structure will slow access to data, and the tools to do this are compiler-dependent. If you want to be portable and efficient, the only way to go is to write fields individually.


Comments