What's the C++ equivalent to Java's java.io.FileInputStream.read()?

How can I turn the following line of Java to C++ code?

 FileInputStream fi = new FileInputStream(f);
 byte[] b = new byte[188];
 int i = 0;
 while ((i = fi.read(b)) > -1)// This is the line that raises my question.
 {
 // Code Block
 }

I'm trying to run the following line of code, but it's result is an error.

 ifstream InputStream;
 unsigned char *byte = new unsigned char[188];
 while(InputStream.get(byte) > -1)
 {
 // Code Block
 }

Upvotes: 1

Views: 3188

Answers (1)

Christophe
Christophe

Reputation: 73500

You can use an std::ifstream, and use either get() to read individual chars one by one, or extraction operator >> to read any given type that would be in plain text in the input stream, or read() to read a consecutive number of bytes.

Note that contrary to the java read() the c++ read returns the stream. If you want to know the number of bytes read, you have to use gcount(), or alternatively use readsome().

So, possible solution could be:

ifstream ifs (f);  // assuming f is a filename
char b[188]; 
int i = 0;
while (ifs.read(b, sizeof(b))) // loop until there's nothing left to read
{
   i = ifs.gcount();   // number of bytes read
   // Code Block
}

Upvotes: 5

Related Questions