Search code examples
qtbinaryfile-copying

What's the best way to copy two binary files in QT


I want to copy one binary file to another binary file. The only constraint I have is that copying must occur through the QFile (because I've overloaded some internal methods and I need them to run). I wrote a naive way to solve but is a slow writer:

QFile * write_to = new QFile("myfile.bin");
if(write_to->open(QFile::WriteOnly))
{
    QFile read_from("my_outher_bin.bin");
    if(read_from.open(QIODevice::ReadOnly))
    {
        QDataStream write_data(write_to);
        QDataStream read_data(&read_from);

        while(write_to->size() < read_from.size())
            write_data << read_data;         
   }
}

What is the most effective way to do this?


Solution

  • An easy and safe way to do it, use the STD libraries, std::ifstream is a good option:

    std::ifstream  src("file.txt", std::ios::binary);
    std::ofstream  dst("to_file.txt",   std::ios::binary);
    dst << src.rdbuf();
    

    If you are using C++17, you can use the <filesystem> extension and use the fs::copy_file function.

    fs::copy_file("file.txt", "to_file.txt");