fscanf()在VSTS中的文件处理中未获取数据

fscanf() is not getting the data in file handling in VSTS

本文关键字:处理 获取 数据 文件 VSTS fscanf      更新时间:2023-10-16

嗨,我有以下代码

# include <stdio.h>
# include <conio.h>
# include <process.h>
void main()
{
    FILE *fp;
    char text[5];
    int age;
    fp=fopen("E:Text1.txt","w+");
    printf("Enter text here and Enter Age :");
    scanf("%s %d",text,&age);
    fprintf(fp,"%s %d",text,age);

    printf("Entered Text and Age is :n");
    fscanf(fp,"%s %d",text,&age);
    printf("Text=%s Age=%d",text,age);
    fclose(fp);
    getche();
}

我对fscanf函数有问题。数据没有显示在输出中。当我尝试调试代码时,它会抛出一个错误,说明"未处理的异常…访问冲突"在这个代码

fscanf(fp,"%s %d",text,&age);

据我所知,我认为VSTS无法获取文件位置。我已经在E驱动器中创建了文件。请帮我解决我的问题。

有两个问题

第一条是路径"E:Text1.txt"=>"E:\Text1.txt"

秒是fopen("E:\Text1.txt","w+");打开该文件写入

如果你想从该文件中读取,那么你应该打开它,用读取

fp=fopen("E:\Text1.txt","r");

因为你用w+打开了它,所以你可以使用

fseek(fp,0,0);

指向文件的开头

   # include <stdio.h>
    # include <conio.h>
    # include <process.h>
    void main()
    {
        FILE *fp;
        char text[5];
        int age;
        fp=fopen("E:\Text1.txt","w+");
        printf("Enter text here and Enter Age :");
        scanf("%s %d",text,&age);
        fprintf(fp,"%s %d",text,age);
        fclose(fp);
        fp=fopen("E:\Text1.txt","r");
        printf("Entered Text and Age is :n");
        fscanf(fp,"%s %d",text,&age);
        printf("Text=%s Age=%d",text,age);
        fclose(fp);
        getche();
    }

另一个版本是

   # include <stdio.h>
    # include <conio.h>
    # include <process.h>
    void main()
    {
        FILE *fp;
        char text[5];
        int age;
        fp=fopen("E:\Text1.txt","w+");
        printf("Enter text here and Enter Age :");
        scanf("%s %d",text,&age);
        fprintf(fp,"%s %d",text,age);
        fseek(fp,0,0);
        printf("Entered Text and Age is :n");
        fscanf(fp,"%s %d",text,&age);
        printf("Text=%s Age=%d",text,age);
        fclose(fp);
        getche();
    }

您的文件路径格式不正确,您应该对其进行双反斜杠:

fp=fopen("E:\Text1.txt","w+");

编辑:经过检查,我意识到你的问题实际上应该与位置指示器有关,一旦你写了,它就设置在文件的末尾,你应该倒带它:

fprintf(fp,"%s %d",text,age);
rewind(fp);