reading a csv file into struct array

前端 未结 3 1434
时光说笑
时光说笑 2021-01-15 13:29

I\'m beginning to code in C. My code is as follows:

#include 
#include 
#include 

#define MAX_STR_LEN 256
#de         


        
相关标签:
3条回答
  • 2021-01-15 13:37

    The problem is your struct:

    struct book{
        int ID;
        char *name;
        char *dateIn;
        char *dateOut;
    };
    

    name, dateIn, dateOut are "pointer", they are just point to something, you're not allocating spaces for them.
    What you do is just point them to tmp(buf).

    So what you do in printBookList() is just print same string block, while ID is OK since it's not pointer.

    To solve this, allocate space for them, you can use strdup(), but make sure to free them.

    0 讨论(0)
  • 2021-01-15 13:39

    The reason is that in something like

    books[i].name = tmp;
    

    You're not actually copying a string from tmp into books[i].name: you just make both point to the same location - somewhere into the buf buffer.

    Try using strdup instead, as in:

    books[i].name = strdup(tmp);
    
    0 讨论(0)
  • 2021-01-15 13:50

    In the while loop:

    while (fgets(buf, 255, bookFile) != NULL)
    

    you are copying into the memory location of buffer new contents from file. As tmp points to a certain point in the buffer, its contents are being replaced too.

     tmp = strtok(NULL, ";");
     books[i].name = tmp;
    

    You should allocate memory for each struct of the array and then use strcopy.

    You can find an explanation of differences between strcpy and strdup here: strcpy vs strdup

    0 讨论(0)
提交回复
热议问题