繁体   English   中英

从文件获取直到行尾

[英]Fgets from the file until end of line

我尝试使用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结构中:

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条件,应该为!= there;
  3. headtail没有宣告。

我希望您有这段代码的有效版本。

关于您的问题,代码按mygets工作mygets函数从文件中读取一行,因此在while(!feof(filename))循环中,您逐行读取文件内容(名称,年龄,高度) ,权重)并将条目放入链接列表。 然后,您只需通过从头到尾遍历链接列表来打印它们。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM