Home > Software engineering >  how can i copy string from file to a linked list in C?
how can i copy string from file to a linked list in C?

Time:12-20

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

CodePudding user response:

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.


PS - If you had compiled your program with warnings turned on, your compiler would have told you there's a problem on that line:

source>: In function 'from_file_to_list':
<source>:29:23: warning: assignment to 'char' from 'char *' makes
integer from pointer without a cast [-Wint-conversion]
   29 |         temp->city[K] = city_name;
      |  
  •  Tags:  
  • c
  • Related