Search code examples
c++fstream

How to measure the remaining bytes on std::fstream?


This is how I open my std::fstream:

    f.open(filePath, std::ios_base::binary | std::ios_base::in |
                                 std::ios_base::out);

After calling some reads, how can I know how much bytes are left to be read?

I think f.tellg() (or tellp?) will tell the current position.

I tried doing some tests:

#include <fstream>
#include <iostream>
#include <vector>

using namespace std;

int main()
{
    std::fstream f;
    std::string filePath = "text.txt";
    f.open(filePath, std::ios_base::binary | std::ios_base::in | std::ios_base::out);
    if (f.is_open()) {
    } else {
        std::cout << "ERROR, file not open";
        return 1;
    }
    //Write some data to vector
    std::vector<char> v;
    v.push_back(1);
    v.push_back(2);
    v.push_back(3);
    v.push_back(4);
    v.push_back(5);
    //Go to beggining of the file to write
    f.seekg(0, std::ios::beg);
    f.seekp(0, std::ios::beg);
    //Write the vector to file
    f.write(v.data(), v.size());
    f.flush();
    //Lets read so we see that things were written to the file
    f.seekg(0, std::ios::beg);
    f.seekp(0, std::ios::beg);
    auto v2 = std::vector<char>(v.size());
    //Read only 3 bytes
    f.read(v2.data(), 3);
    std::cout << "now: " << std::endl;
    std::cout << "f.tellg(): " << f.tellg() << std::endl; 
    std::cout << "f.tellp(): " << f.tellg() << std::endl; 
    std::cout << "end: " << std::endl;
    f.seekg(0, std::ios::end);
    f.seekp(0, std::ios::end);
    f.close();
    return 0;
}

but my file won't open, I get an error. Also, I don't know how to measure the quantity of by


Solution

  • After you've opened the file, you can seekg to the end with f.seekg(0, f.end), then get current position with tellg. This will equal to the total number of bytes in a file.

    Then, you seekg to beginning again, do some reads, and use tellg to get current position. Then, having current position and total file size is easy to calculate the number of bytes left in a file.