用标准c++函数替换QByteArray

Replace QByteArray with std C++ functions

本文关键字:替换 QByteArray 函数 c++ 标准      更新时间:2023-10-16

我正在编写一个简单的二进制文件,它必须包含另一个二进制文件的内容,并在末尾包含这个(另一个)文件的字符串名称。我发现这个样本代码,使用QByteArray从Qt库。我的问题是:是否有可能对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();

然后在末尾写上filename:

dest.write(input.c_str(), input.length()); 

是的,参考fstream/ofstream。你可以这样做:

std::string text = "abcde"; // your text
std::ofstream ofstr; // stream object
ofstr.open("Test.txt"); // open your file
ofstr << text; // or: ofstr << "abcde"; // append text