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);
}
It’s actually very simple… You have a
NODEstructure, which contains anextpointer, and a variableheadwhich points to the head (first node) of the list. The head pointer starts out asNULLmeaning the list is empty.To add a node you create a node, then set the newly created nodes
nextpointer to point to the current head of the list, and set the head to point to the new node:After doing this once, you have a list containing one node. After doing it twice you have a two-node list. Etc.