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

时间:2015-04-03 02:00:30

标签: c++

好的,所以下面的代码应该打开一个二进制文件,并写一些东西到中间元素(在这种情况下,中间的学生)。我最大的问题是,如何在代码中找到我想要实现的“长度”?因为现在它说长度是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();

1 个答案:

答案 0 :(得分:0)

所以我回答了我自己的问题......万一有人在想。我不得不关闭,谢谢你的输入,然后用结构学生划分总大小。 (:

#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();

}