문제

I am using fputc (in C/C++) to output some data into a file, and the file size matters to me in my project. But the size of resutling file seems incorrect, a simple code example:

FILE *fp = fopen( "123.txt", "w" );
for( int i=0; i<64; i++ )
    fputc( i, fp );
fclose( fp );

After excuting this code, the file's size is 65B, not 64B, but if I use fputc(1,fp), the file size is 64B. Is there any trick? or anything I can do to control the size of output file?

도움이 되었습니까?

해결책

I'd guess you're doing this on Windows.

Since you opened the file in translated (text) mode, new-lines are converted to a carriage-return/line-feed pairs. The character code 10 happens to be treated as a new-line, so you end up with an extra byte compared to what you wrote.

If you open the file in binary mode instead, this won't happen.

FILE *fp = fopen( "123.txt", "wb" );

Note the b added to the open mode-string.

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top