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

标签 c scanf

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

这是我的代码:

#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;
}

我尝试了数千次来改变它们,但没有任何效果:/

最佳答案

从此行删除文件:

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

printf()需要 const char *template 作为其第一个参数。

一旦删除,您的代码就可以工作。

关于无法使用 c 中的 fscanf() 从文件中读取字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29194880/

相关文章:

c - EXC_BAD_ACCESS 用 fscanf 加载 int

c - 抢先将文件放入 Windows 页面缓存

关于 c 中的 *(星号) 和++ 的混淆

冲突类型数据定义没有类型或存储类[默认启用]类型默认为 'int'

c - 为什么这个程序的输出是错误的?.数字的频率

c - 从 CSV 文件读取并解决 ";"问题

在c中将字符串转换为 double

c - scanf: "%[^\n]"跳过第二个输入,但 "%[^\n]"不会。为什么?

c - 可以为 scanf ("%x"传递 int 的地址吗,...)?

c - fscanf 将输出写入变量的索引中