gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-28 00:02:10 24 4
gpt4 key购买 nike

如何将下面这行 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 , 并使用 get()一个一个地读取单个字符,或提取运算符 >>读取输入流中纯文本的任何给定类型,或 read()读取连续的字节数。

注意与java read()相反C++ 读取返回流。如果你想知道读取的字节数,你必须使用 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
}

关于java - 与 Java 的 java.io.FileInputStream.read() 等效的 C++ 是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38032800/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com