为什么fwrite在用C编写二进制文件时打印空字节?

为什么fwrite在用C编写二进制文件时打印空字节?,c,C,文件输出: Input text: holiday 您的代码中存在多个问题: 结构的大小是固定的,这解释了为什么输出文件中的字节数比使用的 福卢斯斯丁;具有未定义的行为,不应使用它。没有标准的方法来刷新输入流中的挂起字符,您可以将它们读到换行符,但是如果没有挂起字符,这可能会提示用户进行额外的输入 gets函数已弃用。无法安全地调用它,因为标准库无法确定要存储到目标数组中的最大字符数,因此无法防止可能的缓冲区溢出 以下是更正的版本: 686f 6c69 6461 7900 0000 0000

文件输出:

Input text: holiday

您的代码中存在多个问题:

结构的大小是固定的,这解释了为什么输出文件中的字节数比使用的

福卢斯斯丁;具有未定义的行为,不应使用它。没有标准的方法来刷新输入流中的挂起字符,您可以将它们读到换行符,但是如果没有挂起字符,这可能会提示用户进行额外的输入

gets函数已弃用。无法安全地调用它,因为标准库无法确定要存储到目标数组中的最大字符数,因此无法防止可能的缓冲区溢出

以下是更正的版本:

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 

请注意,可以使用简单的字符数组而不是结构。

两件不相关的事情:首先,永远不要使用gets。这是一个危险的函数,甚至已从C标准中删除。改为使用例如。其次,向[fflush]en.cppreference.com/w/c/io/fflush函数传递类似stdin的纯输入流会导致未定义的行为。有些实现可能允许它作为C语言的扩展,但无论如何都要避免它。你在哪里看到了空格?@Someprogrammerdude-Nah,e是全局静态存储。它是零初始化的。有很多方法可以避免写入空字节。对于字符串形式的文本数据fputse.text,该文件简单有效。若必须使用fwrite,则fwrite.text,1,strlene.text,文件有效。如果必须输出空终止符,请在strlen的结果中添加一个。请注意,写入的不是空格,而是空字节“\0”。
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 
#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;
}