我尝试使用 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
最佳答案
您在问题中发布的代码中有很多错别字和错误。
FILE *f
声明不以分号结尾;while(client!NULL)
中的条件不是有效的 C 条件,它应该是!=
;head
和tail
没有声明。
顺便说一句,我希望你有这段代码的工作版本。
你的问题是什么,代码按照编写的方式工作 - 你的 mygets
函数从文件中读取一行,所以在你的 while(!feof(filename))
循环逐行读取文件内容(姓名、年龄、高度、体重)并将条目放入链表。然后你只需从头到尾遍历链表来打印它们。
关于c - Fgets 从文件直到行尾,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19009772/