c - 将文件内容扫描到链接列表中

标签 c file linked-list

我有一个文件,其中包含公司员工的信息(姓名及其 ID)。 示例文件:

Sailesh 160031158
John 160031145
Sam 160031499

我需要将这些内容扫描到一个链接列表中。如果我知道文件中存在的员工数量(例如“x”),我可以使用以下代码片段将它们存储在链接列表中:

struct node
{
    int id;
    char name[100];
    struct node *next;
}*start=NULL,*new,*prev;

void scan()
{
    fp=fopen("employee_info.c","r");
    for(i=0;i<x;i++)
    { 
        if(start==NULL)
        {
            new=(struct node *)malloc(sizeof(struct node));
            start=new;
            fscanf(fp,"%s%d",new->name,&new->id);
            new->next=NULL;
            prev=new;
        }
        else
        {
            new=(struct node *)malloc(sizeof(struct node));
            fscanf(fp,"%s%d",new->name,&new->id);
            new->next=NULL;
            prev->next=new;
            prev=new;
        }
    }
}

但问题是我应该能够在不知道编号的情况下将文件中的详细信息扫描到链接列表中。在场员 worker 数('x')。

最佳答案

根据 C 文档,方法 fscanf() 具有以下返回值

On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

If a reading error happens or the end-of-file is reached while reading, the proper indicator is set (feof or ferror). And, if either happens before any data could be successfully read, EOF is returned.

因此,不要使用 for 循环,而是尝试将 fscanf 的结果放入 while 循环中并测试 EOF 返回值。像这样的事情:

while(fscanf(fp,"%s%d", new->name, &new->id) != EOF) {
    // Do something
}

关于c - 将文件内容扫描到链接列表中,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42748261/

相关文章:

c - 警告 - 初始化使指针从整数而不进行强制转换

arrays - 为什么我们应该使用堆栈,因为数组或链表可以完成堆栈可以执行的所有操作

linked-list - Julia 中的双链表

c - 从文件读取到链表 C

c - 应用程序正在使用哪些环境变量

c - getpeername函数的理解

c - 将结构传递给函数并在 C 中修改它

c++ - 存储在文件中的记录

javascript - 如何确定 JavaScript 中的文件大小?

python - 在 python 3.x 中有效地搜索多个文件的关键字的最佳方法?