C++中fstream的read问题。
天蓬老师
天蓬老师 2017-04-17 13:02:47
0
1
705
 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;
}

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

天蓬老师
天蓬老师

欢迎选择我的课程,让我们一起见证您的进步~~

reply all(1)
阿神

There is an answer on Stackoverflow (http://stackoverflow.com/questions/22984956/tellg-function-give-wrong-size-of-file)

The main meaning is that the number returned to you by tellg is not used to calculate the size, but is used when you want to seek the same place in the future. It also gives a correct method to calculate the file size:

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 );
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template