Reputation: 24765
I'm trying to write-to-disk an array containing 11.26 million uint16_t values. The total memory size should be ~22 MB. However, the size of my file is 52MB. I'm using fprintf to write the array to disk. I thought maybe the values were being promoted. I tried to be explicit but it seems to make no difference. The size of my file is stubbornly unchanged.
What am I doing wrong? Code follows.
#define __STDC_FORMAT_MACROS
...
uint32_t dbsize = 11262336;
uint16_t* db_ = new uint16_t[dbsize_];
...
char fname[256] = "foo";
FILE* f = fopen(fname, "wb");
if(f == NULL)
{
return;
}
fprintf(f, "%i\t", dbsize_);
for(uint32_t i = 0; i < dbsize_; i++)
{
fprintf(f, "%" SCNu16 "", db_[i]);
}
fclose(f);
Upvotes: 0
Views: 272
Reputation: 10978
The source of confusion is likely to be that the "b" in FILE* f = fopen(fname, "wb");
does not do what you think it does.
Most significantly, it doesn't change any of the print or scan statements to use binary values instead of ASCII values. Like others have said - use fwrite
instead.
Upvotes: 2
Reputation: 12287
You're writing ASCII to your file, not binary.
Try writing your array like this instead of using fprintf
in a loop.
fwrite(db_, sizeof(db_[0]), dbsize, f);
fprintf
always formats numbers and other types to text, whether you've opened the file in binary mode or not. Binary mode just keeps the runtime from doing things like converting \n
to \r\n
.
Upvotes: 8
Reputation: 100668
fprintf
will convert you number to a series of ASCII characters and write them to a file. Depending on its value, a 32-bit int will be from 1 to 10 characters long when expressed as a string. You need to use fwrite
to write raw binary values to a file.
Upvotes: 2