#include <stdio.h>
struct my_struct {
char text[100];
} e;
int main() {
FILE *file;
file = fopen("filename", "ab+");
if (file == NULL) {
file = fopen("filename", "wb+");
}
printf("Input text: ");
fflush(stdin);
gets(e.text);
fwrite(&e, sizeof(e), 1, file);
fclose(file);
return 0;
}
我在这里想做的是创建一个二进制文件并通过用户输入的文本写入该文件。代码运行良好!唯一的问题是该文件包含空格,我认为这是由于 fwrite
在写入文件时传递的 struct my_struct
的数组大小造成的。我找不到删除空格或替换 fwrite
的好方法。谢谢你!来回答这个问题。
程序输出:
Input text: holiday
文件输出:
686f 6c69 6461 7900 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000 0000 0000 0000 0000 0000 0000
0000 0000
最佳答案
您的代码中存在多个问题:
struct
的大小是固定的,这解释了为什么您在输出文件中获得的字节数多于所使用的字节数。
<fflush(stdin);
具有未定义的行为,您不应使用它。没有标准方法可以刷新输入流中待处理的字符,您可以将它们读取到换行符,但是如果没有待处理的字符,这可能会提示用户输入额外的输入。gets()
函数已弃用。它无法安全地调用,因为标准库无法确定要存储到目标数组中的最大字符数,因此它无法防止可能的缓冲区溢出。
这是更正后的版本:
#include <stdio.h>
#include <string.h>
struct my_struct {
char text[100];
} e;
int main() {
FILE *file = fopen("filename", "ab");
if (file == NULL) {
file = fopen("filename", "wb");
}
if (file == NULL) {
printf("Cannot open filename\n");
return 1;
}
printf("Input text: ");
if (fgets(e.text, sizeof e.text, stdin)) {
/* strip the trailing newline if any */
e.text[strcspn(e.text, "\n")] = '\0';
/* write the bytes to the binary file */
fwrite(e.text, strlen(e.text), 1, file);
}
fclose(file);
return 0;
}
请注意,您可以使用简单的 char
数组代替结构。
关于c - 为什么在 C 中写入二进制文件时 fwrite 会打印空字节?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48368514/