【发布时间】:2016-06-05 10:03:59
【问题描述】:
我无法将 .txt 文件中的数据保存和加载到动态数组中。
我的整个程序都是基于 switch 语句的。 我将只在此处粘贴负责为数组分配内存并调用函数以用结构填充它的案例。以及保存和加载数据的功能。
代码如下所示
case 1:
system("cls");
printf("Enter amount of students you want to put in data base\n");
scanf("%d",&number_of_students);
student=(data*)malloc(number_of_students*sizeof(data));
adding_students_to_base( number_of_students); // its a simple functions based on for loop. I don't think that posting it here is necessary
break;
和功能:
void saving_base_to_file(int amount_of_students)
{
FILE *file;
system("cls");
printf("Saving base to file!\n");
file=fopen("database.txt","wb");
fprintf(file,"%d",amount_of_students); // function also saves amount of students in base
fwrite(student,sizeof( data),amount_of_students,file);
fclose(file);
_getch();
system("cls");
}
void loading_base_from_file()
{
FILE *file;
system("cls");
printf("Reading base from file\n");
file=fopen("database.txt","rb");
if (file!= NULL) {
fscanf(file,"%d",&number_of_students);
fread(&student,sizeof( data),number_of_students,file); //number_of_students is global variable
student=(data*)malloc(number_of_students*sizeof(data));
fclose(file);
}
else
{
printf("File does not exist!.\r\n");
printf("File have to be named ""database.txt"" !!!\n");
}
_getch();
system("cls");
}
(函数 Saving_base_to_file 将 number_of_students 作为输入参数。)
当我想使用“loading_base_from_file”函数时出现问题
例如,当我想保存一个名为“Greg”“Tesla”的学生ID为“123456”的学生时,文件包含以下内容: database.txt。函数 save_base_to_file 还保存了基础中的学生数量。但是当我再次启动我的程序(或在一个程序运行中执行它)并尝试从文件中加载数据时,我的函数“print_base”会打印这个: result
我认为将数据“放入”数组中存在问题,但我不知道到底出了什么问题。 你能告诉我为什么会发生这种情况以及如何解决它吗?
【问题讨论】:
-
在同一个文件句柄上使用
fscanf/fprintf和fread/fwrite很难说是个坏主意。 -
不要将
malloc和朋友的结果投射到 C 中!
标签: c arrays file-io structure