为什么文件存储二进制字符? getw() 和 putw() 被要求在问题中使用

Why is the file storing binary characters? getw() and putw() were asked to be used in the question

我在读写文件时使用了“.txt”扩展名,并且文件模式对应于“文本”类型的文件。该程序运行良好,但不是在文件中存储 ASCII 字符,而是存储二进制字符。我在这里需要一些帮助。谢谢你。

int main(void)
{
    FILE *fp;
    int n2, n1;
    printf("ENTER A NUMBER: ");
    scanf("%d", &n1);
    fp = fopen("hello.txt", "w");
    if (fp == NULL)
    {
        printf("ERROR");
        exit(1);
    }
    fprintf(fp, "%d", n1);
    //fclose(fp);
    //rewind(fp);
    fp = fopen("hello.txt", "r");
    if (fp == NULL)
    {
        printf("ERROR");
        exit(1);
    }
    //n2 = getw(fp);
    fscanf(fp, "%d", n1);
    printf("%d", n1);
    fclose(fp);
}

您应该在 fscanf 中发送变量地址,如下所示:

fscanf(fp,"%d",&n1);

如果您要关闭并重新打开文件,则不需要 rewind。或者你可以打开文件进行读写,然后就可以使用rewind。两者都有效,这是后者的示例:

int main(void)
{
    FILE *fp;
    int n2, n1;
    printf("ENTER A NUMBER: ");
    if (scanf("%d", &n1) == 1) // checking if the input was correctly parsed
    {
        fp = fopen("hello.txt", "w+"); // open to read and write
        if (fp == NULL)
        {
            printf("ERROR");
            exit(1);
        }
        putw(n1, fp); // write to the file

        rewind(fp); // go back to the beginning of the file

        n2 = getw(fp);    // get the data

        printf("%d", n2);
        fclose(fp);
    }
    else
    {
        puts("Bad input");
    }
}

Live sample

stdin读取时还有可能出现整数溢出的问题,如果不需要防范的话,至少要记录下这个漏洞,否则建议使用fgets 读取输入,strtol 转换值。