【发布时间】:2016-03-14 13:46:16
【问题描述】:
所以我正在尝试编写具有学生记录数据库的 ac 文件,一旦文件运行,它应该从二进制文件中读取学生记录并将它们添加到链表中:学生结构如下所示:
typedef struct student {
char lname[10], initial, fname[10];
unsigned long SID;
float GPA;
struct student* next; /* pointer to the next student record */
} studentList;
我对我的数据使用单链表,如果我使用 fscanf 读写数据,我的代码运行良好。但是,一旦我开始使用 fwrite 和 fread,每次我的程序加载它都不会正确加载文本文件中的数据,当我检查二进制文件时,它似乎有数据。这是我的加载和写入数据功能:
void printRecords() {
FILE *fPointer = fopen("data.bin", "w");
studentList *newStudent = head;
while (newStudent != NULL) { /*Loop through linked list starting from head node*/
fwrite(&newStudent, sizeof(newStudent), 1, fPointer);
newStudent = newStudent->next;
}
}
void loadRecords() {
studentList *cStudent;
FILE *fPointer = fopen("data.bin", "r");
int counter = 0;
int x = 0;
int n = 0;
while (n != 0) {
printf("test\n");
if (fPointer == NULL) {
break;
}
cStudent = (studentList *)malloc(sizeof(studentList));
n = fread(&cStudent, sizeof(cStudent), 1, fPointer);
x = cStudent->GPA;
printf("%d\n", x);
if (feof(fPointer)) { break; }
if (counter == 0) {
head = cStudent;
temp = (studentList *)malloc(sizeof(studentList));
temp = cStudent;
counter++;
}
temp->next = (studentList *)malloc(sizeof(studentList));
temp->next = cStudent;
temp = temp->next;
}
fclose(fPointer);
}
所以我做错了什么,因为现在它没有将任何内容读入我的列表,它似乎在写入但不确定它是否甚至写入了正确的数据,我花了很长时间试图弄清楚这一点并拥有卡了一段时间了,先谢谢了。
【问题讨论】:
-
你还没有关闭
printRecords()中的文件