c - 为什么在 C 中写入二进制文件时 fwrite 会打印空字节?

标签 c

#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/

相关文章:

c - 缓冲区大小不正确

c - 如何在 OS X 上读取其他应用程序文本字段的内容?

c - C标准是否对INT_MIN和INT_MAX之间的关系做出保证?

c - 如何生成0到1之间的随机 float

c - 使用 scanf 连续读取字符串和 int 时遇到问题

c - 将 SDL 与 Win32 窗口结合使用

c - 如何在 Visual Studio 2019 中创建 C 项目?

c - 当我们找到答案时退出先前的递归

在 C 中使用 printf 自定义字符串对齐

c - malloc 时我应该使用什么作为 sizeof 的参数