ifstream::read 不告诉它真正读取了多少字节?

ifstream::read doesn't tell how many bytes it really reads?

本文关键字:读取 多少 字节 read ifstream      更新时间:2023-10-16

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

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

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

您可以使用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();

因为CCD_ 5返回CCD_。