如何将带有分隔符的文件行中的单词存储到结构中

How to store words from file line with separators into a struct

我有一个名为 cstats.txt 的输入文件,它只有一行:

name:age:phone:city

我有一个公民结构:

typedef struct {             
    char name[100];          
    int age;               
    char city[100]
    char phone[10];   
} Citizen;  

我需要从文件中读取并将属性保存在结构中:

我试过了:


Citizen a;
fread(a, sizeof(Citizen), 1, "cstats.txt");

但我认为它没有保存属性。

我在这里搜索了 SO,但我发现的只是逐行阅读。

谢谢!

fread 不是这项工作的最佳(最简单)工具,请改用 fgets

读取整行,然后用类似sscanf的方式解析字段,例如:

char line[250];

Citizen a;

FILE *file = fopen("cstats.txt", "r");

if (file != NULL)
{
    if (fgets(line, sizeof line, file))
    {
        sscanf(line, "%99[^:]:%d:%9[^:]:%99[^\n]", a.name, &a.age, a.phone, a.city);
    }
}

关于 fread,它的一个很好的用例是从 fwrite 写入的文件中读取数据,这将保证数据被适当格式化以直接读取到一个像用来写的缓冲区,例如:

Citizen a;
Citizen b;

FILE *file = fopen("file.txt", "w+"); // open to read and write

fwrite(&a, sizeof a, 1, file); // write Citizen a to file
fseek(file, 0, SEEK_SET);      // reset file position indicator
// rewind(file);               // alternative
fread(&b, sizeof b, 1, file);  // read data directly to Citizen b

在上面的代码中,为了简单起见,我跳过了 return 值检查,你应该在你的代码中这样做。

Live demo