无法使用c中的fscanf()从文件中读取字符串

时间:2015-03-22 13:21:27

标签: c scanf

我尝试编写从现有文件中读取struct内容的代码,但它没有显示人类可读的内容

这是我的代码:

#include <stdio.h>
#include <stdlib.h>

struct Student{
    char studentName[30];
    char studentLast[30];
};

int main()
{
    struct Student s1,s2;
    FILE *file = fopen("test.txt", "r");
    if (file==NULL){
        printf("Error Reading students");
        return 1;
    }
    while(1){
        int cnt=fscanf(file, "%s\t%s\t\n", &s1.studentName, &s1.studentLast);
        if (cnt == -1)
            break;
        printf(file, "%s\t%s\t\n", s1.studentName, s1.studentLast);
    }

    fclose(file);
    return  0;
}

我尝试了几千次来改变它们根本没有任何作用:/

2 个答案:

答案 0 :(得分:3)

从此行中删除文件:

    printf(file, "%s\t%s\t\n", s1.studentName, s1.studentLast);

printf()期望将const char *模板作为其第一个参数。

删除后,您的代码就可以运行。

答案 1 :(得分:1)

首先,正如@MarianoMacchi强调的那样,编译器抱怨printf(file, "%s\t%s\t\n", s1.studentName, s1.studentLast);应该是printf("%s\t%s\t\n", s1.studentName, s1.studentLast);fprintf(file_open_with_w_or_a,"%s\t%s\t\n", s1.studentName, s1.studentLast);,但我想这行会被添加到调试中,或者提供一个最小的示例

Athoner问题是int cnt=fscanf(file, "%s\t%s\t\n", &s1.studentName, &s1.studentLast);应该是:

int cnt=fscanf(file, "%29s\t%29s\t\n", s1.studentName, s1.studentLast);

fscanf()需要指向要读取的数据的指针。因此,如果是整数,则为:int a;fscanf(file,"%d",&a);。对于字符串,它需要指向第一个字符的指针:

char s[42];
fscanf(file,"%41s",&s[0]);

或等效地:

char s[42];
fscanf(file,"%41s",s);`.

可以添加要读取的最大项目数,以避免在输入较大时出现未定义的行为。 fscanf()返回成功读取的项目数,因此循环可以退出cnt!=2

我建议采用以下循环:

while(1){
    int cnt=fscanf(file, "%29s\t%29s\t\n", s1.studentName, s1.studentLast);
    if (cnt != 2)
        break;
    printf("%s\t%s\t\n", s1.studentName, s1.studentLast);
}