C++ 将fread()应用于局部结构变量后函数返回时发生访问冲突
这是我节目的一部分C++ 将fread()应用于局部结构变量后函数返回时发生访问冲突,c++,file-io,struct,fread,C++,File Io,Struct,Fread,这是我节目的一部分 void LookUpStuInfo(student stu[], int size, int ID) { FILE *fp; if((fp = fopen("stu_dat", "r")) == NULL) { cout << "cannot open file" << endl; return; } struct student tmp; fread(
void LookUpStuInfo(student stu[], int size, int ID)
{
FILE *fp;
if((fp = fopen("stu_dat", "r")) == NULL)
{
cout << "cannot open file" << endl;
return;
}
struct student tmp;
fread(&tmp, sizeof(struct student), 1, fp);
fclose(fp);
}
我已经测试过删除程序中的所有
字符串,效果很好。似乎fread()
会在对string
进行操作的函数中出错。您不能fread
放入std::string
中,如student.name
(或从中写入)。崩溃发生的原因是您有一个已损坏的字符串,当编译器试图将其复制到数组中时,一切都发生了可怕的错误。直接读入数组不会有帮助,因为您可能计划在某个点访问数组的成员-在该点上,所有内容都会再次死亡
您需要读入字符串的长度,然后读入字符串的字符。tmp
在函数结束时超出范围。您需要发布问题的完整示例。如果没有这一点,任何解决方案实际上都只是猜测。读到tmp
然后什么都不做有什么意义?这个函数只不过是无缘无故地打开和关闭一个文件。就其本身而言,我怀疑这是您的问题的原因。您在提问时似乎简化了实际代码。这很好,但我担心你已经把问题简化了。这个实际代码是否显示了问题?请包括与您的问题无关的main代码,但我仍然建议FILE*fp=fopen(“stu_dat”,“r”);如果(fp==NULL)
和sizeof(tmp)
而不是sizeof(struct student)
。这不是我唯一的“风格”评论,但对于初学者来说已经足够了。
#include<iostream>
#include<string>
#include "stdio.h"
#define num 3
using namespace std;
struct student
{
int ID;
string name;
string sex;
string birthday;
float score;
};
void SortStuArr(student stu[], int size)
{
student tmp;
for (int i = 0; i < size; i++)
for (int j = (i + 1); j < size; j++)
{
if (stu[i].score < stu[j].score)
{
tmp = stu[i];
stu[i] = stu[j];
stu[j] = tmp;
}
}
cout << "ID" << " " << "Score" << endl;
for (int i = 0; i < size; i++)
cout << stu[i].ID << "\t" << stu[i].score << endl;
}
float GetAvgScr(student stu[], int size)
{
float avg=0;
for (int i = 0; i < size; i++)
avg += (stu[i].score);
avg = avg / size;
return avg;
}
void LookUpStuInfo(const char* locat, int size, int ID)
{
FILE *fp;
if((fp=fopen("stu_dat","r"))==NULL)
{
cout << "cannot open file" << endl;
return;
}
struct student tmp;
for (int i = 0; i < size; i++)
{
fread(&tmp, sizeof(struct student), 1, fp);
if (tmp.ID == ID)
{
cout << tmp.name << tmp.ID << tmp.sex << tmp.birthday << tmp.score << endl;
fclose(fp);
}
}
cout << "Not Found!" << endl;
fclose(fp);
}
void WritetoFile(student stu[], int size)
{
FILE *fp;
if((fp=fopen("stu_dat","w+"))==NULL)
{
cout << "cannot open file" << endl;
return;
}
for (int i = 0; i < size; i++)
fwrite(&stu[i], sizeof(struct student), 1, fp);
fclose(fp);
}
int main()
{
student stu[num];
for (int i = 0; i < num; i++)
{
cin >> stu[i].name >> stu[i].ID >> stu[i].sex >> stu[i].birthday >> stu[i].score;
}
cout << GetAvgScr(stu, num) << endl;
WritetoFile(stu, num);
LookUpStuInfo("stu_dat", num, 1000);
return 0;
}