文件读取失败,vs2019 无法打开文件,是源文件这里错了吗?
void readStudentFile(struct Student** head) {
FILE* file = fopen("students.txt", "r");
if (file == NULL) {
printf("无法打开文件\n");
return;
}
char line[100]; // 假设每行最多100个字符
//读文件,写文件
while (fgets(line, sizeof(line), file) != NULL) {
char studentId[10], name[50], password[20];
int balance;
if (sscanf(line, "%s %s %s %d", studentId, name, password, &balance) == 4) {
// 格式正确,创建新的学生节点
struct Student* newStudent = (struct Student*)malloc(sizeof(struct Student));
if (newStudent == NULL) {
printf("内存分配失败\n");
fclose(file);
return;
}
// 将学生信息复制到新节点中
strcpy(newStudent->studentId, studentId);
strcpy(newStudent->name, name);
strcpy(newStudent->password, password);
newStudent->balance = balance;
newStudent->next = NULL;
// 将新的学生节点添加到链表中
addStudent(head, newStudent);
}
else {
printf("文件格式错误\n");
}
}
fclose(file);
}