与 Java 的 java.io.FileInputStream.read() 等效的 C++ 是什么?

Luc*_*urt 1 c++ java inputstream

如何将以下 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
 }
Run Code Online (Sandbox Code Playgroud)

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

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

Chr*_*phe 5

您可以使用std::ifstream, 并使用get()逐个读取单个字符,或使用提取运算符>>读取输入流中纯文本形式的任何给定类型,或read()读取连续数量的字节。

请注意,与java相反,read() c++ read 返回流。如果您想知道读取的字节数,您必须使用gcount(),或者使用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
}
Run Code Online (Sandbox Code Playgroud)