[英]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
您在問題中張貼的代碼中有很多錯別字和錯誤。
FILE *f
聲明不以分號結尾; while(client!NULL)
中的條件不是有效的C條件,應該為!=
there; head
和tail
沒有宣告。 我希望您有這段代碼的有效版本。
關於您的問題,代碼按mygets
工作mygets
函數從文件中讀取一行,因此在while(!feof(filename))
循環中,您逐行讀取文件內容(名稱,年齡,高度) ,權重)並將條目放入鏈接列表。 然后,您只需通過從頭到尾遍歷鏈接列表來打印它們。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.