我希望在编写函数时能得到一些帮助。在一个单独的头文件中,我有一个结构。它的结构如下:
typedef struct data{
int id;
char name[100];
char text[200];
struct data *next;
}listData;
使用这个结构,我试图用文件中的数据填充列表,该文件的格式为
id,名称,文本\n
我的功能原型如下:
void loadDataFromFile(listData** dataList);
由于每个变量之间都有逗号,我不知道如何在不出错的情况下将文件读取到列表中。
有人有什么想法吗?
您可以尝试读取文件,然后逐行读取,然后使用strtok((按逗号分隔行
char read_buffer[] = "File content";
char * file_content = read_buffer;
while(file_content) {
char * next_line = strchr(file_content, 'n');
if (next_line) *next_line = ' '; // Terminate next line so you can read the current line
char * answer = strtok(file_content, ","); // Split the current line by comma
answer = strtok(NULL, ","); // Gets the next value after first comma, do with rest on the line
if (nextLine) *nextLine = 'n'; // Bring the next line back
config = nextLine ? (nextLine+1) : NULL; // Config is equal to the next line (if it exists)
}