DFH:Sizeof(Object) 使用 fin.seekg() 给出奇怪的输出;
DFH: Sizeof(Object) giving weird output with fin.seekg();
函数如下:
void debugged_read()
{
clrscr();
stu S1;
ifstream fin;
eof=false;
fin.open("CP2.dat", ios::binary); //Opens the file again
while(fin.eof() == false) {
cout<<"\n\n Initial location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads a Record into fin stream
S1.show();
cout<<"\n\n After Read location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads the next record space for eof detection
cout<<"\n Check position: "<<fin.tellg();
if(fin.eof() == true) {
cprintf("\nWARNING: End of file Incoming!");
break; //Break on eof encounter
}
else {
fin.seekg(-(sizeof(S1)), ios :: cur); //File Pointer Correction
cout<<"\n File Pointer Corrected: "<<fin.tellg();
}
}
cout<<"\nRead Successful!";
fin.close();
}
如果我使用 long 变量存储 'stu' class 的对象 S1 的大小,此函数将返回预期输出。
但使用 sizeof();它直接给出了这个奇怪的输出:
sizeof
returns size_t 即 unsigned int
istream::read
期望 streamsize 即 signed int
函数如下:
void debugged_read()
{
clrscr();
stu S1;
ifstream fin;
eof=false;
fin.open("CP2.dat", ios::binary); //Opens the file again
while(fin.eof() == false) {
cout<<"\n\n Initial location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads a Record into fin stream
S1.show();
cout<<"\n\n After Read location: "<<fin.tellg();
fin.read((char*)& S1, sizeof(S1)); //Reads the next record space for eof detection
cout<<"\n Check position: "<<fin.tellg();
if(fin.eof() == true) {
cprintf("\nWARNING: End of file Incoming!");
break; //Break on eof encounter
}
else {
fin.seekg(-(sizeof(S1)), ios :: cur); //File Pointer Correction
cout<<"\n File Pointer Corrected: "<<fin.tellg();
}
}
cout<<"\nRead Successful!";
fin.close();
}
如果我使用 long 变量存储 'stu' class 的对象 S1 的大小,此函数将返回预期输出。
但使用 sizeof();它直接给出了这个奇怪的输出:
sizeof
returns size_t 即 unsigned int
istream::read
期望 streamsize 即 signed int