【问题标题】:ifstream::read doesn't tell how many bytes it really reads?ifstream::read 不知道它真正读取了多少字节?
【发布时间】:2012-07-28 02:01:36
【问题描述】:

我正在使用ifstream::read 读取文件,

ifstream ifs("a.txt");
char buf[1024];
ifs.read(buf, 1024);

但是a.txt的大小可能小于1000 bytes,那我怎么知道从ifs读取了多少字节呢?

【问题讨论】:

    标签: c++ ifstream readfile


    【解决方案1】:

    你可以通过std::ifstream::gcount获取最后一次操作提取的字符数量:

    ifstream ifs("a.txt");
    char buf[1024];
    ifs.read(buf, 1024);
    size_t extracted = ifs.gcount();
    

    ifstream ifs("a.txt");
    char buf[1024];
    size_t extracted = ifs.read(buf, 1024).gcount();
    

    因为read(...) 返回*this

    【讨论】:

      猜你喜欢
      • 2023-02-16
      • 2012-10-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2012-01-17
      相关资源
      最近更新 更多