ifstream :: read不能告诉它真正读取多少字节?
问题描述:
我使用 ifstream :: read
读取档案,
ifstream ifs("a.txt");
char buf[1024];
ifs.read(buf, 1024);
但是a.txt的大小可能小于 1000字节
,所以我应该知道从 ifs
?中读取了多少字节?
But a.txt's size might be less than 1000 bytes
, so how am I supposed to know how many bytes have been read from ifs
?
答
您可以使用 std :: ifstream :: gcount :
You can get the amount of characters extracted by the last operation with 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
。