FILE *out=fopen64("text.txt","w+"); unsigned int write; char *outbuf=new char[write]; //fill outbuf printf("%i\n",ftello64(out)); fwrite(outbuf,sizeof(char),write,out); printf("%i\n",write); printf("%i\n",ftello64(out));
输出:
0 25755 25868
到底是怎么回事?
写入设置为25755,我告诉fwrite写一个文件,这是开头,然后im在一个位置除了25755以外的许多字节?
解决方法
如果您使用的是DOSish系统(例如Windows),并且文件未以二进制模式打开,则会自动转换行尾,并且每个“行”将添加一个字节.
所以,指定“wb”作为模式,而不是只是“w”,因为@caf指出.它将对Unix平台没有影响,并且会对其他人做正确的事情.
例如:
#include <stdio.h> #define LF 0x0a int main(void) { char x[] = { LF,LF }; FILE *out = fopen("test","w"); printf("%d",ftell(out)); fwrite(x,1,sizeof(x),out); printf("%d",ftell(out)); fclose(out); return 0; }
用VC:
C:\Temp> cl y.c Microsoft (R) 32-bit C/C++ Optimizing Compiler Version 15.00.21022.08 for 80x86 Copyright (C) Microsoft Corporation. All rights reserved. y.c Microsoft (R) Incremental Linker Version 9.00.21022.08 Copyright (C) Microsoft Corporation. All rights reserved. /out:y.exe C:\Temp> y.exe 04
用Cygwin gcc:
/cygdrive/c/Temp $gcc y.c -o y.exe /cygdrive/c/Temp $./y.exe 02