c - Fgets 从文件直到行尾

标签 c fgets

我尝试使用 mygets 函数,这样 fgets 将只读取一行:

void * mygets(char *name, int len, FILE * stream)
{
    fgets(name,len,stream);

    if (name[strlen(name) - 1] == 10)
    {
        name[strlen(name) - 1] = 0;
    }
}

文件内容为:

John Smith //Name

19 // Age

175.62 // Height

87  // Weight

使用单链表,我只希望 *mygets 只读直到 John Smith 然后将它存储到一个名为 client 通过:

typedef struct nodebase{
    char name[40]; //Just in case, the client's name can be long
    int age;
    double height;
    int weight;
    struct nodebase *next;
    }listnode;

int main()
{
listnode *head;
listnode *tail;
listnode *client;
FILE *f;

f=fopen("filename.txt","r");

while(!feof(filename))
{
    client = malloc(sizeof(listnode));
    mygets(client->name,40,filename);

    if (head == NULL)
    {
        head = client;
    }
    else 
    {
        tail->next=client;
    }
    tail = client;
    client =head;
}

while(client!=NULL)
{
    printf("\n%s\n",&client->name);
    client = client->next;
}

}

但问题是,程序打印了整个文件(包括年龄、高度和体重)。

我找不到我的 *mygets 有什么问题。

***我在 Windows 上使用 Tiny C

最佳答案

您在问题中发布的代码中有很多错别字和错误。

  1. FILE *f 声明不以分号结尾;
  2. while(client!NULL) 中的条件不是有效的 C 条件,它应该是 !=
  3. headtail 没有声明。

顺便说一句,我希望你有这段代码的工作版本。

你的问题是什么,代码按照编写的方式工作 - 你的 mygets 函数从文件中读取一行,所以在你的 while(!feof(filename)) 循环逐行读取文件内容(姓名、年龄、高度、体重)并将条目放入链表。然后你只需从头到尾遍历链表来打印它们。

关于c - Fgets 从文件直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009772/

相关文章:

c - 从 C 字符串中提取 POST 参数

c - 非可移植指针转换

C - fgets() - 换行符的长度

C - 在函数中使用 fgets() 从标准输入读取行

c - 如何在 C 中禁用 GtkTextView 的编辑?

c - 没有它们如何获取 GetProcAdress 和 LoadLibrary?

c - 如何使用 fgets() 从 stdin 读取?

c - 使用 feof() 从文件读取并退出循环

c++ - 如何使用 openMP 将顺序程序转换为并行程序?

c - 如何修复嵌套在 if-else 中的 while 循环?