Reading .csv file into C LinkedList

限于喜欢 提交于 2019-12-08 09:52:49

问题


I have the following struct:

struct NODE {
    char username[50];
    char password[50];
    char usertype[50];
    struct NODE *next;
} *head=NULL;

I would like to read from a .csv file, say database.csv of the form username, password, usertype, tokenize each line into tokens using strtok and put each token inside the right field. For instance, my file looks like this:

johnnydepp, pirate123, user
tonystark, iron456, sysop

I keep reading on C LinkedList, but I cannot figure it out. Any help would be greatly appreciate, or any good references on how to implement a LinkedList in C.

My main problem is putting element in the each of the node. I know how to use strtok to tokenize a line in a file. This is what I have done so far:

void createList() {
    FILE *data;
    data = fileopen("password.csv", "r");
    char parsedLine[50];
    while (fgets(parsedLine, 50, data) != NULL) {
    char *ptr = strtok(parsedLine, ", ");
        node *temp;
        temp = (node*)malloc(sizeof(node));
    // I am stuck here //
} 

Thanks!

EDIT

Will this work?

extern void createList() {

FILE *data;
data = fileopen("password.csv", "r");
char parsedLine[50];
while (fgets(parsedLine, 50, data) != NULL) {
    struct NODE *node = malloc(sizeof(struct NODE));
    char *getUser = strtok(parsedLine, ", ");
    strcpy(node->username, getUser);
    char *getPass = strtok(NULL, ", "); 
    strcpy(node->password, getPass);
    char *getType = strtok(NULL, ", ");
    strcpy(node->usertype, getType);    
    node->next = head;
    head = node;
}
fclose(data);

}

回答1:


It's actually very simple... You have a NODE structure, which contains a next pointer, and a variable head which points to the head (first node) of the list. The head pointer starts out as NULL meaning the list is empty.

To add a node you create a node, then set the newly created nodes next pointer to point to the current head of the list, and set the head to point to the new node:

/* Allocate new node */
struct NODE *node = malloc(sizeof(struct NODE));

/* Link to the current head */
node->next = head;

/* Make the new node the head of the list */
head = node;

After doing this once, you have a list containing one node. After doing it twice you have a two-node list. Etc.



来源:https://stackoverflow.com/questions/13465264/reading-csv-file-into-c-linkedlist

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!