Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ifstream, bytes read?

Tags:

c++

How do you get how many bytes were read with the ifstream::read function?

Tell is saying the file is 10 bytes and windows says it is 10 bytes too but there are only 8 bytes in the file so when I read it, it is only reading the 8 bytes so I end up with too large of a buffer.

like image 345
user230821 Avatar asked Dec 20 '09 22:12

user230821


People also ask

What does the read function do in C++?

The read() function reads data previously written to a file. If any portion of a regular file prior to the end-of-file has not been written, read() shall return bytes with value 0. For example, lseek() allows the file offset to be set beyond the end of existing data in the file.

How do I read a CPP file?

File Handling in C++ To read a character sequence from a text file, we'll need to perform the following steps: Create a stream object. Connect it to a file on disk. Read the file's contents into our stream object.

What is ifstream in C++?

ifstream is an input file stream. It is a special kind of an istream that reads in data from a data file. ofstream is an output file stream. It is a special kind of ostream that writes data out to a data file.


2 Answers

You can find out by calling gcount() on a stream immediately after you read.

ifs.read(buf, sizeof buf); std::streamsize bytes = ifs.gcount(); 
like image 106
Alex B Avatar answered Sep 19 '22 20:09

Alex B


There is a function called readsome(...) that does what you want:

streamsize readsome ( char* s, streamsize n ); 

Return Value The number of characters extracted.

like image 21
Khaled Alshaya Avatar answered Sep 20 '22 20:09

Khaled Alshaya