如何测量std::fstream上的剩余字节数?

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

这就是我打开 std::fstream 的方式:

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

调用一些读取后,如何知道还有多少字节要读取?

我认为f.tellg()(或tellp?)会告诉当前位置。

我试着做了一些测试:

#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;
}

但是我的文件打不开,出现错误。另外,我不知道如何测量 by

的数量

打开文件后,您可以seekg使用f.seekg(0, f.end)结束,然后使用tellg获取当前位置。这将等于文件中的总字节数。

然后,您 seekg 重新开始,进行一些读取,然后使用 tellg 获取当前位置。然后,有了当前位置和总文件大小就很容易计算出文件中剩余的字节数。