【问题标题】:Replace QByteArray with std C++ functions用标准 C++ 函数替换 QByteArray
【发布时间】:2017-01-20 16:10:00
【问题描述】:

我正在编写一个简单的二进制文件,该文件必须包含另一个二进制文件的内容以及该(另一个)文件末尾的字符串名称。 我从 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();

【问题讨论】:

    标签: c++ qt qbytearray


    【解决方案1】:

    是的,请参考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
    

    【讨论】:

      【解决方案2】:

      以二进制模式打开您的文件并通过 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

      【讨论】:

        猜你喜欢
        • 2017-04-08
        • 2021-05-05
        • 2012-02-24
        • 2018-08-12
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多