简体   繁体   中英

how can i copy string from file to a linked list in C?

Hi guys i can't copy text from a file to linked list, with integers there is no problem. There is my code. Main problem is to copy year of visit and name of city to a linked list like, I'm new in programming and tbh i can't get a lot of things. Pointers seems very hard to me

#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);
}

This line:

temp->city[K] = city_name;

doesn't actually copy a string. To copy a string in C, you have to copy each one of its characters in a loop, or alternatively use a function like strcpy() or strncpy() .

Remember to make sure the string is not longer than the amount of space you have available at the destination.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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