[英]How can I create a linked list of characters read from a file? C language
[英]how can i copy string from file to a linked list in C?
大家好,我無法將文本從文件復制到鏈表,整數沒有問題。 有我的代碼。 主要問題是將訪問年份和城市名稱復制到鏈接列表中,例如,我是編程新手,但我無法獲得很多東西。 指針對我來說似乎很難
#include <stdio.h>
#include <stdlib.h>
#define K 50
typedef struct tourists{
int year;
char city[K];
char country[K];
struct tourists *next;
}Element;
typedef Element *List;
List from_file_to_list(char file_name[20])
{
FILE *file1;
int x, y;
char city_name[K];
List temp, head = NULL;
file1 = fopen(file_name, "r");
if(file1 == NULL)
{
printf("Cannot do that");
return NULL;
}
while(fscanf(file1, "%d %s", &x, city_name) != EOF)
{
temp = (List)malloc(sizeof(Element));
temp->city[K] = city_name;
temp->year = x;
temp->next = head;
head = temp;
}
return head;
}
void show_list(List head)
{
List temp;
temp = head;
while(temp != NULL)
{
printf("%s", temp->city);
temp = temp->next;
}
}
int main()
{
List head = NULL;
head = from_file_to_list("from.txt");`
show_list(head);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.