写入二进制文件的中间;使用tellg()查找长度



好的,下面的代码应该打开一个二进制文件,并向中间的元素(在本例中为中间的Student)写入一些内容。我最大的问题是,如何找到我试图在代码中实现的"长度"?因为现在它说长度是0,我需要根据文件的大小来改变这个长度

编辑。哦,我希望长度以"学生"的数量为单位

感谢您的任何意见。

 struct Student{
char Name[20];
int Age;
float GPA;
};

int main(){
Student A;
Student B;
Student C;
fstream out1("Test.bin", ios::out | ios::binary);
out1.write((char*)&A, sizeof(Student));
out1.write((char*)&B, sizeof(Student));
out1.write((char*)&C, sizeof(Student));
Student objRead;
fstream in("Test.bin", ios::in | ios::binary);
in.seekg(0, in.end);
int length = in.tellg();
in.seekg(0, in.beg);
cout << length;
in.seekg(((length/2)-1)*sizeof(Student), ios::beg);
in.read((char*)&objRead, sizeof(Student));
in.close();

所以我回答了自己的问题。。。万一有人想知道。我不得不结束,感谢你的输入,然后用结构Student除以总大小。(:

#include <iostream>
#include <fstream>
using namespace std;
struct Student{
int Age;
float GPA;
};
int main(){
Student A;
A.GPA = 4.0;
A.Age = 3;
Student B;
B.GPA = 4.0;
B.Age = 5;
Student C;
C.GPA = 4.0;
C.Age = 3;
fstream out1("Test.bin", ios::out | ios::binary);
out1.write((char*)&A, sizeof(Student));
out1.write((char*)&B, sizeof(Student));
out1.write((char*)&C, sizeof(Student));
out1.close();
Student objRead;
fstream in("Test.bin", ios::in | ios::binary);
in.seekg(0, in.end);
int length = in.tellg();
int reallength = length / sizeof(Student); 
in.seekg(0, in.beg);
cout << reallength;
in.seekg(((reallength/2)-1)*sizeof(Student), ios::beg);
in.read((char*)&objRead, sizeof(Student));
in.close();
Student temp;
fstream out("Test.bin", ios::out |ios::in| ios::binary);
out.seekg((reallength - 4)*sizeof(objRead), ios::beg);
out.read((char*)&temp, sizeof(Student));
out.seekp((reallength - 4)*sizeof(objRead), ios::beg);
out.write((char*)&objRead, sizeof(Student));
out.seekp(((reallength / 2) - 1)*sizeof(Student), ios::beg);
out.write((char*)&temp, sizeof(Student));
out.close();

}

最新更新