C++中fstream的read问题。

浏览:29日期:2023-06-01

问题描述

int main(){ fstream file1; char buffer[512]; char c; file1.open('66666.txt', ios::in); file1.seekg(0, ios::end); string::size_type file_size = file1.tellg(); cout<<file_size<<endl; file1.seekg(0, ios::beg); for(;;){file1.read(buffer, 512);cout<<file1.gcount()<<endl;cout<<file1.tellg()<<endl;if(file1.eof()){ break;} } file1.close(); cin>>c; return 0;}

C++中fstream的read问题。

以上是我的代码和结果,我这个程序的目的是每次读取文件中的512个字节,输出是首先输出这个文件的总字节数,然后每次读的时候输出所读入的字节数以及当前get 流指针的位置。我第一次读512字节之后,当前get流指针的位置不应该是512吗,为什么这个程序却跑出了533的结果?

问题解答

回答1:

Stackoverflow上有解答(http://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file)

主要的意思就是,tellg返回给你的那个数字不是用来计算大小的,而是用来给你在以后想seek到同一个地方的时候使用的。同时也给出了一个计算文件尺寸的正确方法:

file.ignore( std::numeric_limits<std::streamsize>::max() );std::streamsize length = file.gcount();file.clear(); // Since ignore will have set eof.file.seekg( 0, std::ios_base::beg );

相关文章: