Java 的 java.io.FileInputStream.read() 在 C++ 中的等价物是什么?

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

如何将下面的 Java 行转换为 C++ 代码?

 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
 }

我正在尝试 运行 以下代码行,但结果是错误的。

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

您可以使用 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() 来读取连续的字节数。

注意与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()

因此,可能的解决方案可能是:

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
}