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

可紊 提交于 2019-12-30 08:12:11

问题


I'm using ifstream::read to read a file,

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

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?


回答1:


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();

or

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

since read(...) returns *this.



来源:https://stackoverflow.com/questions/11720880/ifstreamread-doesnt-tell-how-many-bytes-it-really-reads

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!