如何在二进制文件中附加二进制文件C++

How to append binary file with a binary file in C++

本文关键字:二进制文件 C++      更新时间:2023-10-16

我有两个二进制文件,我想将一个与另一个一起附加。我该怎么做?

std::ofstream outFile;
outFile.open( "file.bin", ? );

巢线应该是什么?

有一个行

std::ofstream outFile("file.out", std::ios::ate );
std::ifstream inFile( "file.in" );
std::copy( 
    (std::istreambuf_iterator<char>(inFile)),  // (*)
     std::istreambuf_iterator<char>(),
     std::ostreambuf_iterator<char>(outFile)
);

(*) 额外的一对括号,以防止将其解析为函数声明。

为了获得更好的性能,您可以使用ifstream::read分块读取文件,并使用ofstream::write写入它们。

这不是最理想的,但您可以尝试如下方法:

std::ofstream outFile( "file.bin", ios_base::app | ios_base::out );
std::ifstream inFile(source_file_name, ios_base::binary | ios_base::in);
source >> noskipws;
char c;
while (inFile >> c) {
    outFile << c;
}

您可以通过使用更大的缓冲区来提高效率。