【发布时间】:2018-01-18 03:41:04
【问题描述】:
- 我不允许使用向量,因为我的教学大纲中没有教授它
我正在做一项关于学生作业分数的读/写/存储的作业。
我在下面使用 2 个结构
struct assessTask
{
char title [MAX];
int weight;
int markUpon;
float mark;
};
struct subject
{
char code [MAX];
char title [MAX];
int numTask;
assessTask task [MAX];
int finalMark;
UNIGrade grade;
};
我的 write 函数的简短片段:(请告诉我这种风格是否正确/错误)
// run if code is unique
strcpy(s[size].code, testcode);
afile.write (reinterpret_cast <const char *>(&s[size].code), sizeof (s));
cin.clear();
cin.ignore(MAX, '\n');
cout << "Subject Name: ";
cin.getline(s[size].title, MAX);
afile.write (reinterpret_cast <const char *>(&s[size].title), sizeof (s));
cout << "No of assessment tasks: ";
cin >> s[size].numTask;
afile.write (reinterpret_cast <const char *>(&s[size].numTask), sizeof (s));
Snippet of whats inside my binary file .dat
所以,在我退出程序后,.dat 将被存储以备将来使用。 每次我打开程序时,它都会检查.dat文件,我可以用它来通过程序查询或更新
void checkBinary(fstream& afile, const char fileName [], subject s[])
{
afile.open(fileName, ios::in | ios::binary);
int g = 0;
while (afile.read (reinterpret_cast <char *>(&s), sizeof (s)))
{
g++;
}
cout << g << endl;
if (g < 1)
{
createBinary (afile, "subject.dat", s);
}
else
{
readBinary (afile, "subject.dat", s);
}
afile.close();
}
void createBinary (fstream& afile, const char fileName [], subject s[])
{
afile.open (fileName, ios::out | ios::binary);
cout << "Begin the creation of binary file " << fileName << endl;
afile.write (reinterpret_cast <const char *>(&s), sizeof (s));
afile.close ();
cout << "Binary file " << fileName
<< " successfully created"
<< endl;
}
void readBinary (fstream& afile, const char fileName [], subject s[])
{
afile.open (fileName, ios::in | ios::binary);
afile.clear();
afile.seekg(0, ios::end);
int size = afile.tellg();
int noOfRecords = size / sizeof (s);
afile.seekg(0, ios::beg);
while (afile.tellg() < noOfRecords)
{
afile.read (reinterpret_cast <char *>(&s), sizeof (s));
/*
afile.read (reinterpret_cast <char *>(&s[start].code), sizeof (s));
afile.read (reinterpret_cast <char *>(&s[start].title), sizeof (s));
afile.read (reinterpret_cast <char *>(&s[start].numTask), sizeof (s));
for (int i = 0; i < s[start].numTask; i++)
{
afile.read (reinterpret_cast <char *>(&s[start].task[i].title), sizeof (s));
afile.read (reinterpret_cast <char *>(&s[start].task[i].weight), sizeof (s));
afile.read (reinterpret_cast <char *>(&s[start].task[i].markUpon), sizeof (s));
}
*/
}
afile.close();
}
出于某种原因,我必须在 readbinary() 中使用 afile.clear(),否则返回给我的字节为 -1。
我现在遇到的问题是我需要从 .dat 文件中复制信息并将其存储在某个位置,以便在程序的连续使用期间,我仍然能够检索数据并在 s[] 时显示它.code 已输入。
注意事项:
- 我正在附加到 .dat,而不是覆盖
- 我有一个查询功能,可以在用户输入主题代码时读回数据
- 我尝试在 readbinary() 中使用 cout 来查看它是否读取任何内容。它只是给了我一个空行
- 我听说我需要将读取的信息存储回数组结构中,但我不知道如何
仍然是 C++ 的业余爱好者,如果我不了解某些上下文,请提前道歉
感谢任何帮助。谢了!
【问题讨论】:
-
对我来说毫无意义的一件事是文件名和
fstream的传递。如果你应该创建一个文件,主题来自哪里?aFile是否可能是您的源数据来自哪里,而 `fileName 是您需要读取或写入数据的位置?这种 API 设计没有多大意义:-/ -
我使用文件将数据读/写到文件名中,即我的 subject.dat
标签: c++ arrays data-structures struct binary