[英]Reading .csv file into C LinkedList
I have the following struct
: 我有以下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. 我想从阅读.csv
文件,说database.csv
形式的username, password, usertype
,记号化各线进入使用令牌strtok
,把每个令牌右场里面。 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. 我一直在阅读C LinkedList
,但我无法LinkedList
。 Any help would be greatly appreciate, or any good references on how to implement a LinkedList
in C. 任何帮助都会非常感激,或者有关如何在C中实现LinkedList
任何好的参考。
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. 我知道如何使用strtok
来标记文件中的一行。 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 NODE
structure, which contains a next
pointer, and a variable head
which points to the head (first node) of the list. 它实际上非常简单......你有一个NODE
结构,它包含一个next
指针, next
指向列表头部(第一个节点)的变量head
。 The head pointer starts out as NULL
meaning the list is empty. 头指针以NULL
开头,表示列表为空。
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: 要添加节点,请创建节点,然后将新创建的节点的next
指针设置为指向列表的当前头部,并将头部设置为指向新节点:
/* 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. 等等。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.