iHubble
iHubble

Reputation: 186

Reading .csv file into C LinkedList

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

}

Upvotes: 2

Views: 6764

Answers (1)

Some programmer dude
Some programmer dude

Reputation: 409216

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.

Upvotes: 3

Related Questions