c++ - 将多个文件段复制到一个文件中 - Qt

标签 c++ c linux windows qt

我有一个文件分成许多段。我必须将这些文件组合成一个文件。现在我想到的简单代码是:

 QFile file;
 file.setFileName(fileUrl);
 file.open(QIODevice::WriteOnly);
 for(int j=0;j<totalSegments;j++)
 {
     Segment[j]->fileSegment.close();
     if(!Segment[j]->fileSegment.open(QIODevice::ReadOnly))
     {
        qDebug()<<"Segment not found";
        continue;
     }
     file.write(Segment[j]->fileSegment.readAll());  // is this really efficient and safe
     Segment[j]->fileSegment.close();
     Segment[j]->fileSegment.remove();
 }

上面的代码片段在 Windows 和 Linux 上都运行良好。但我有一些问题:

1- 这种方法真的有效吗?如果假设段大小以 GB 为单位,这将严重影响系统的性能,甚至可能损坏文件或由于可用 RAM 不足而失败。

2- 如果总大小超过 2GB,上述方法在某些 Linux 发行版尤其是 Fedora 中会失败。我自己没有测试过,但很多人向我报告过。

3- 在 Linux 中,如果段位于 EXT4 文件系统上并且目标文件将在 NTFS 系统上写入该文件,它会失败吗?它在 Ubuntu 上没有失败,但许多用户提示它失败了。我不能只是复制它。我是不是做错了什么。

最佳答案

一般来说,请避免每个问题有多个子问题,但无论如何我都会尽量回答你的问题。

1- Is this method really efficient. If suppose the segment size is in GB's will this badly affect the performance of the system, or can even corrupt the file or fail due to less available RAM.

对于大文件来说这是个非常糟糕的主意。我想你希望建立chunk文件读写。

2- The above method fails in some Linux Distro's especially Fedora if total size is more than 2GB. I haven't tested myself but was reported to me by many.

2 GB <(或者是 4 GB?)在 32 位系统上算作大文件,因此他们可能使用没有大文件支持构建的软件。有必要确保在构建时启用支持。 Qt 曾经有一个配置选项 -largefile

3- In Linux can it fail if segments are on an EXT4 filesystem and target file into which the file will be written on NTFS system. It didn't fail on Ubuntu but many users are complaining that it does. I can't just replicate it. Am I doing something wrong.

是的,这可能是同样的问题,您还需要注意内存碎片,这意味着,即使您有 2 GB 可用内存,您也无法在内存中分配 2 GB,但内存碎片不当。在 Windows 上,您可能希望使用 /LARGEADDRESSAWARE 选项,例如在使用 32 位进程时。

总的来说,最好是建立读写循环,这样就可以忘记大地址感知等问题了。如果您希望为您的客户支持大文件,您仍然需要确保 Qt 可以处理大文件。这当然只在 32 位上是必需的,因为此时对于 64 位当前正在进行的文件大小没有实际限制。

由于您在评论中请求了一些代码来帮助您前进,这里是一个简单且未经测试的 block 读取版本,并将内容从输入文件立即写入输出文件。我相信这会让你继续下去,这样你就可以解决剩下的问题。

QFileInfo fileInfo("/path/to/my/file");
qint64 size = fileInfo.size();
QByteArray data;
int chunkSize = 4096;
for (qint64 bytes = 0; bytes < size, bytes+=data.size()) {
    data = myInputFile.read(chunkSize);
    // Error check
    myOutputFile.write(data);
}

关于c++ - 将多个文件段复制到一个文件中 - Qt,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23702626/

相关文章:

C++ Qt - 当类 T 的属性具有父级时的奇怪行为是 T

c++ - 将 Fortran 用户定义类型转换为 C++ 类

html - 随机文章按钮

c - 这个带线程的程序是如何工作的?

c++ - 使用 C++ 和 OpenGL 设置的 Mandelbrot 中的错误着色

c++ - boost::scoped_ptr 到引用的转换失败

c - 使用 GtkClipboard 获取 URL

linux - 在 Linux 中,有一系列假定按顺序命名的文件,我如何进行检查以验证所有文件是否确实存在?

linux - 从 Shell 脚本调用 makefile

Linux:有没有办法为所有打印到显示器的输出加上时间戳?