zac*_*caj 13 c file fwrite ftell
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));
Run Code Online (Sandbox Code Playgroud)
输出:
0
25755
25868
Run Code Online (Sandbox Code Playgroud)
到底是怎么回事?write设置为25755,我告诉fwrite将多个字节写入文件,这是在开头,然后我在25755以外的位置?
Sin*_*nür 25
如果您使用的是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;
}
Run Code Online (Sandbox Code Playgroud)
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
/cygdrive/c/Temp $ gcc y.c -o y.exe /cygdrive/c/Temp $ ./y.exe 02
| 归档时间: |
|
| 查看次数: |
10456 次 |
| 最近记录: |