C++ 以二进制模式将文件中的块读取到缓冲区,然后将该缓冲区写入另一个文件

C++ 以二进制模式将文件中的块读取到缓冲区,然后将该缓冲区写入另一个文件,c++,ifstream,ofstream,C++,Ifstream,Ofstream,我正在努力实现这样的目标: while (ifstream has not been entirely read) { read a chunk of data into a buffer that has size BUFLEN write this buffer to ostream } while (a chunk larger than zero could be read) { write chunk to output } 起初,我试图通过使用ifstream.e

我正在努力实现这样的目标:

while (ifstream has not been entirely read)
{
   read a chunk of data into a buffer that has size BUFLEN
   write this buffer to ostream
}
while (a chunk larger than zero could be read)
{
  write chunk to output
}
起初,我试图通过使用
ifstream.eof()
作为while条件来实现这一点,但我听说这不是解决问题的方法。我一直在研究std::ios::ifstream的其他函数,但不知道还可以使用什么


PS:我正在使用缓冲区,因为正在传输的文件可能会变得非常大。

您的逻辑完全错误

你需要这样做:

while (ifstream has not been entirely read)
{
   read a chunk of data into a buffer that has size BUFLEN
   write this buffer to ostream
}
while (a chunk larger than zero could be read)
{
  write chunk to output
}

看看这怎么会更简单?无需显式检查“文件结束”,只需读取数据直到失败。然后就完成了。

函数返回流,该流可用作布尔表达式,因此可以执行以下操作:

while (is.read(buffer, BUFLEN))
{
    outputfile.write(buffer, is.gcount());
}

if (is.eof())
{
    if (is.gcount() > 0)
    {
        // Still a few bytes left to write
        outputfile.write(buffer, is.gcount());
    }
}
else if (is.bad())
{
    // Error reading
}

您可能需要检查循环内的写入是否也失败。

iostream类负责所有必要的缓冲,因此您不需要 不得不复制整个文件的常用习惯用法是:

fout << fin.rdbuf();
这是相当丑陋的;更好的解决方案可能是将缓冲区包装在
类,并定义一个
运算符,以了解您的意思。我试图通过使用read()作为条件来实现这一点,但read()给出了一个空文件,并且!read()一直在重写我的文件,副本之间有垃圾。你介意详细说明并给我具体的函数来使用吗?下面的代码给了我一个空的新文件,也许你知道它的问题是什么<代码>while(is.read(buffer,BUFLEN)){outfile.write(buffer,BUFLEN);}
感谢示例代码Joachim。这似乎也适用于其他文件,如pdf等!因此,如果我必须读取一个非常大的文件并将其写入其他文件,我就不必担心使用缓冲区,iostream已经这样做了吗?但是,我这样做是因为我在稍后的阶段通过TCP发送数据。谢谢你的代码,我现在就来试试。还有一点需要注意:当我处理非文本文件时,这是否也适用?因为我需要能够与任何类型的文件(pdf,mp3,…)这样做。它似乎对我测试过的pdf不起作用。只要你以二进制方式打开输入和输出文件,它就可以对任何文件起作用。@Retired Ninja够奇怪的了,它似乎对我的示例pdf不起作用。我使用一个字符缓冲区[BUFLEN]作为缓冲区。我只将buf.size()改为BUFLEN。如果读取没有失败,那么如何设置
readCount
呢?是否应将其初始化为
buf.size()