[英]Fgets from the file until end of line
I tried using mygets function so that the fgets will only read one 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;
}
}
And the file content is: 文件内容为:
John Smith //Name
19 // Age
175.62 // Height
87 // Weight
Using single linked-list, I just wanted the *mygets
to read only until John Smith
then store it to a typedef struct named client
by: 使用单个链接列表,我只希望*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;
}
}
But the problem is, the program prints the entire file (including the age, height, and weight). 但是问题是,程序会打印整个文件(包括年龄,身高和体重)。
I cannot find anything wrong with my *mygets
. 我的*mygets
找不到任何问题。
***I am using Tiny C on Windows ***我在Windows上使用Tiny C
You have lots of typos and mistakes in the code you have posted in your question. 您在问题中张贴的代码中有很多错别字和错误。
FILE *f
declaration doesn't end with semicolon; FILE *f
声明不以分号结尾; while(client!NULL)
is not valid C condition, it should be !=
there; while(client!NULL)
中的条件不是有效的C条件,应该为!=
there; head
and tail
did not declared. head
和tail
没有宣告。 I hope that by the way you have working version of this code. 我希望您有这段代码的有效版本。
What is about your question, the code just works as it is written - your mygets
function reads a line from the file, so in your while(!feof(filename))
loop you read file contents line by line (name, age, height, weight) and put entries into the linked-list. 关于您的问题,代码按mygets
工作mygets
函数从文件中读取一行,因此在while(!feof(filename))
循环中,您逐行读取文件内容(名称,年龄,高度) ,权重)并将条目放入链接列表。 Then you just print them by traversing linked list from beginning to the end. 然后,您只需通过从头到尾遍历链接列表来打印它们。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.