coin cheung
coin cheung

Reputation: 1105

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

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 ?

Upvotes: 3

Views: 249

Answers (2)

Build Succeeded
Build Succeeded

Reputation: 1150

Below is link for details as I think return type of file_size needs to typecast: https://www.codingame.com/playgrounds/5659/c17-filesystem

Upvotes: 0

coin cheung
coin cheung

Reputation: 1105

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.

Upvotes: 1

Related Questions