【问题标题】:Loading structure from txt file to dynamic array将结构从txt文件加载到动态数组
【发布时间】: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/fprintffread/fwrite 很难说是个坏主意。
  • 不要将malloc 和朋友的结果投射到 C 中!

标签: c arrays file-io structure


【解决方案1】:

您使用student 表明它是一个指针。这意味着当您在变量上使用地址运算符& 时,您将获得指向变量存储位置的指针,而不是指向您分配的内存的指针。 &student 的类型是 data ** 而不是 data *

仅此一项就会导致未定义的行为,因为您将数据写入内存中不应该存在的地方,但这不是唯一的问题。另一个问题是你为student分配内存你从文件中读取数据,使student完全指向其他地方,也让你丢失数据你刚读过。

首先分配内存,然后读入student(而不是&student)。


还有另一个问题,那就是你混合了文本数据和二进制数据。如果结构中的第一个元素包含可以解析为文本数字的值,则读取文件中记录数的初始数字在读取时将不正确。

你需要fwrite这个号码,然后fread它回来。

【讨论】:

  • 谢谢,案件结案!
猜你喜欢
  • 2016-06-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-04-15
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多