我正在编写一个简单的二进制文件,该文件必须包含另一个二进制文件的内容和末尾这个(另一个)文件的字符串名称。
我发现这个示例代码使用了 Qt 库中的 QByteArray
。我的问题是:是否可以对 std c++ 函数做同样的事情?
char buf;
QFile sourceFile( "c:/input.ofp" );
QFileInfo fileInfo(sourceFile);
QByteArray fileByteArray;
// Fill the QByteArray with the binary data of the file
fileByteArray = sourceFile.readAll();
sourceFile.close();
std::ofstream fout;
fout.open( "c:/test.bin", std::ios::binary );
// fill the output file with the binary data of the input file
for (int i = 0; i < fileByteArray.size(); i++) {
buf = fileByteArray.at(i);
fout.write(&buf, 1);
}
// Fill the file name QByteArray
QByteArray fileNameArray = fileInfo.fileName().toLatin1();
// fill the end of the output binary file with the input file name characters
for ( int i = 0; i < fileInfo.fileName().size();i++ ) {
buf = fileNameArray.at(i);
fout.write( &buf, 1 );
}
fout.close();
最佳答案
以二进制模式打开文件并通过 rdbuf 进行“一次”复制:
std::string inputFile = "c:/input.ofp";
std::ifstream source(input, std::ios::binary);
std::ofstream dest("c:/test.bin", std::ios::binary);
dest << source.rdbuf();
然后在最后写上文件名:
dest.write(input.c_str(), input.length());
你可以找到更多的方法here .
关于c++ - 用标准 C++ 函数替换 QByteArray,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39463567/