c - 将 fscanf 传递给结构

标签 c

我正在尝试打开一个文件并传递给 struct,我正在使用带有循环的 fscanf(),但它只保存了一个 struct 最后读取:

想象一个文件:

JR John Rambo 24353432 
JL John Lennon 6435463

我正在使用这段代码:

typedef struct people{
    char code[10];
    char name[100];
    long telephone;
}PEOPLE;

int read(PEOPLE people[], int n_p){
    char temp;
    FILE *fp;
    fp=fopen("example.txt","r");
    if(fp==NULL){
        printf("Error\n");
        return -1;
    }
    while(!feof(fp)){
        fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].name,
               &people[n_p].telephone);
    }
}

问题是他只保存文件的最后一行...我应该做一个 if cicle 吗??

另一个问题是如何分隔类似的文件但用“;”

最佳答案

首先,当您在 fscanf 中仅传递 3 个参数时,您正在扫描 3 个字符串 (%s) 和一个 int (%d) ()。您可以在 struct 中添加 char first_name[50];,然后执行以下操作:

fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].first_name,
         people[n_p].name, &people[n_p].telephone);

你总是 fscanf() 文件直到你没有更多可读的东西(由于 !feof(fp) 因为 while。所以在最后 people[n_p] 变量文件的最后一行将被保存。

您可以从 read() 中删除 while 并将 FILE * 作为参数添加到函数中,这样您就不会每次调用 read() 时都不要打开文件。

可能是这样的:

main()
{
   FILE* fp = fopen("example.txt", "r");
   int i = 0;

   while (!feof(fp)) {
       read(people, i, fp);
       i++;
   }
}

int read(PEOPLE people[], int n_p, FILE* fp){
   char temp;

   if(fp==NULL){
       printf("Error\n");
       return -1;
   }
   fscanf(fp,"%s %s %s %d\n", people[n_p].code,people[n_p].first_name, 
         people[n_p].name, &people[n_p].telephone);

}

要使用 ; 作为分隔符,您可以将 fscanf() 更改为:

 fscanf(fp, "%[^;]; %[^;]; %d\n", people[n_p].code,people[n_p].name,
             &people[n_p].telephone);

编辑 我写了上面的代码,可以找到here它与这个 example.txt file 配合得很好作为输入。

关于c - 将 fscanf 传递给结构,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5956477/

相关文章:

c - 需要展开循环宏

c - 基本创建队列崩溃

c - Eratosthenes 输出误差筛

c - 按位与运算符 & 的作用是什么?

我可以写入非常量结构的 const 成员吗?

c - 使用 ld 链接已编译的程序集和 C 文件

c - 如何在c中检查一行文本中的某些字符

c - 用户尝试停止服务时出现警告窗口

c - gtree 中的值错误

c - Flex 在 C 中使用管道