c++ - 用标准 C++ 函数替换 QByteArray

标签 c++ qt qbytearray

我正在编写一个简单的二进制文件,该文件必须包含另一个二进制文件的内容和末尾这个(另一个)文件的字符串名称。 我发现这个示例代码使用了 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/

相关文章:

c++ - 从 Qt 对话框中删除 "?"-button

c++ - 将 NULL 视为 QByteArray 中的字符

c++ - 添加(而不是连接)一个数字到 QByteArray

c++ - 我可以按任意顺序在 QGraphicsScene 中堆叠对象吗?

c++ - 在if语句中将多个字符变量转换为数字

c++ - 什么 VS2010 C 项目设置导致 exes 需要兼容模式

c++ - 将 Qt 与 WinForms 集成以使用某些类

c++ - 视觉 C++ 14 CTP3 : c++11 inheriting constructor bug?

c++ - Qt 有资源系统限制吗?

c++ - 如何将 QImage 转换为 QByteArray?