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

问题描述

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

enter image description here

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,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读取时仍然存在可能的整数溢出问题,如果不需要防范,请确保至少记录该漏洞,否则建议使用{{1} } 读取输入,fgets 转换值。