Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

get wrong file size with c++ ios::ate

Tags:

c++

fstream

I am trying to get the file size of a file with c++. The code is like this:

 ifstream fin(filepth, ios::in | ios::binary | ios::ate);
    if (!fin.is_open()) {
        cout << "cannot open file:" << filepth << endl;
    }
    int len = fin.tellg();
    fin.seekg(0, ios::beg);
    fin.clear();
    cout << "file length is: " << len << endl;
    cout << "file length is: " << fs::file_size(fs::path(filepth)) << endl;

It turns out that the method of ios::ate got the wrong result. What did I miss and how could I got the correct result ?

like image 574
coin cheung Avatar asked Apr 02 '26 03:04

coin cheung


1 Answers

I got the reason of the problem. My file is about 9 gigabytes long, which cannot be expressed by a 32 bit int variable. I used int64_t and the problem no longer exists.

like image 160
coin cheung Avatar answered Apr 03 '26 17:04

coin cheung



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!