Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/cplusplus/151.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C++ 如何测量std::fstream上的剩余字节?_C++_Fstream - Fatal编程技术网

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

C++ 如何测量std::fstream上的剩余字节?,c++,fstream,C++,Fstream,这就是我如何打开我的std::fstream: f.open(filePath, std::ios_base::binary | std::ios_base::in | std::ios_base::out); 调用一些读取后,我如何知道还有多少字节需要读取 我想f.tellg()(或tellp?)会告诉你当前的位置 我试着做了一些测试: #include <fstream> #include <ios

这就是我如何打开我的
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;
}
#包括
#包括
#包括
使用名称空间std;
int main()
{
std::fsf;
std::string filePath=“text.txt”;
f、 打开(文件路径,std::ios_base::binary | std::ios_base::in | std::ios_base::out);
如果(f.是开着的()){
}否则{

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


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

“我的文件无法打开,我遇到错误”-是否存在
test.txt
文件?如果文件不存在,
binary | in | out
组合将失败,请参见文档中的表格。很难判断还有多少流需要读取。通常,编写程序的目的是保持读取,直到找到它要查找的内容或什么都没有。此外,因为文件流am实现内部缓冲,因此缓冲区中有多少字节并不一定反映基础文件中还有多少字节未读。最好的选择是事先获得文件大小,然后跟踪到目前为止从流中读取的字节数,在需要时从大小中减去该值。@user4581301但h如何获取文件大小?我在Android上运行,std::filesystem还没有准备好。使用tellg获取整个文件大小不也会遇到同样的问题吗?