【发布时间】:2023-08-17 15:20:02
【问题描述】:
我正在尝试将一些用户输入以二进制格式写入文件。当我查看文件时,我希望只看到 0 和 1,但文件的输出以普通文本打印:
FILE *f;
char array[8];
f = fopen("numbers.bin", "ab+");
if(f==NULL){
printf("Could not open file!\n");
system("pause");
exit(1);
}
for(i=0;i<numberOfInputs;i++){
printf("\nEnter number nr %i:", i+1);
gets(array); //get the input and place it in array
strcat(array, "\n"); // add a newline to the input
fwrite(array,sizeof(char),1,f); //write output to the file
}
有没有人能发现我在这里做错了什么?
【问题讨论】:
-
您期望“只有 0 和 1”?!你想做什么?用户是否应该输入数字(更准确地说是整数)并且您想以(依赖于操作系统的)二进制格式附加这些数字?还是您想按原样附加带有附加换行符的字符串?
-
不要使用gets。如果文件中有超过 8 个字符的行,则说明缓冲区溢出。
-
由于缓冲区溢出的原因,当当前版本的标准 (C11) 发布时,gets() 最近已从 C 语言中删除。使用 gets() 的程序将无法在未来的 C 编译器上编译。