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

时间:2013-11-24 10:40:00

标签: c++ c visual-studio-2010

您好我有以下代码

# 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 Drive中创建了该文件。请帮我解决问题。

2 个答案:

答案 0 :(得分:1)

你有两个问题

首先是路径"E:\Text1.txt"=>"E:\\Text1.txt"

sec 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();
    }

答案 1 :(得分:0)

你的文件路径没有正确格式化,你应该加倍反斜杠:

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

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

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