简体   繁体   中英

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
 }

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
}

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