简体   繁体   中英

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

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 ?

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM