Timofey Chernikov
Timofey Chernikov

Reputation: 55

Binary file size bigger than expected c++

this code creates file with size of 2338 bytes

ofstream ofs("out", ios::binary);
ofs << htonl(1);
int size = sizeof(htonl(1));
for(int i = 0; i < 500; i++){
    ofs << htons((unsigned short)(sin(i/5)*1000));
    size += sizeof(htons((unsigned short)(sin(i/5)*1000)));
}
cout << "file size : " << size << endl;
ofs.close();

but output is "file size : 1004" why file size isn't actually 1004 bytes?

Upvotes: 2

Views: 704

Answers (2)

Slava
Slava

Reputation: 44288

but output is "file size : 1004" why file size isn't actually 1004 bytes?

Because std::ostream::operator<<() output number in text format, so for example number 1 takes 1 byte, number 1000 takes 4 etc. sizeof() gives you size of data type in bytes. Those are unrelated numbers and you cannot expect them to match.

If you want to write binary data, use std::ostream::write() - then your numbers would match (but you cannot read that file by a text editor).

Upvotes: 2

Sander De Dycker
Sander De Dycker

Reputation: 16243

If you open the file in a text editor, you'll quickly see what's wrong.

The numbers are being printed in their decimal representation, and not written as their internal (binary) representation.

Instead, use ostream::write :

uint32_t foo = htonl(1);
ofs.write(reinterpret_cast<char*>(&foo), sizeof(foo));

Upvotes: 5

Related Questions