void readDataFromFile(President **h) {
FILE *fp = fopen("President.txt", "r");
if (fp == NULL) {
printf("Cannot open a file!\n");
return;
}
char buffer[MAX];
int rno, start_date, end_date;
char name[MAX];
while(fgets(buffer, MAX, fp) != NULL) {
// Reading data from line
if (sscanf(buffer, "%d %[^\n] %d-%d", &rno, name, &start_date, &end_date) != 4) {
printf("Error trying to read file!\n");
fclose(fp);
return;
}
// Creating of new node
President *newNode = (President*)malloc(sizeof(President));
if (newNode == NULL) {
printf("Memory error!\n");
fclose(fp);
return;
}
newNode->rno = rno;
strcpy(newNode->name, name);
newNode->start_date = start_date;
newNode->end_date = end_date;
newNode->next = NULL;
// Adding new node to list
if (*h == NULL) {
*h = newNode;
} else {
President* current = *h;
while (current->next != NULL) {
current = current->next;
}
current->next = newNode;
}
}
fclose(fp);
printf("Data is added to list!\n");
}
你好.我试图从一个文件读到另一个链表,但我总是得到一个错误原因if(Sscanf).我的代码出了什么问题?我已经判断了几次文件中的文本,但它是好的,但无论如何都不能读它.我能有一些帮助或一些有用的链接吗?如果你告诉我我可以在哪里读到它,我准备自己管理它.
以下是输入文件中的三条采样线
1 President 2000-2004
2 President 1932-1957
3 President 2012-2016