【问题标题】:Not reading all binary data from file不从文件中读取所有二进制数据
【发布时间】:2018-05-24 21:03:28
【问题描述】:

在一个项目中,我需要从文件中读取二进制数据并使用gzip解压缩。问题是QFile::readAll() 实际上并没有读取所有字节,也没有报告任何错误。

这是我的代码:

QFile ifile("/tmp/currentAlmanac.gz");
qDebug() << "File Size:" << ifile.size();

ifile.open(QIODevice::ReadOnly);
QByteArray data = ifile.readAll();
ifile.close();
qDebug() << "Almanac Size:" << data.size();

输出是:

文件大小:78637
年历大小:78281

是不是我做错了什么?

有大量可用内存。

规格:Ubuntu16.04 上的 Qt5.10

【问题讨论】:

  • 您是否尝试验证文件的内容?磁盘上的文件大小及其实际字节数可能因文件系统、磁盘压缩等不同而有所不同。
  • @Azeem 我需要解压缩它并且原始文件解压缩工作,而 QByteArray 缺少一些数据。我已经尝试再次从 nasa 下载年历,再次解压缩和压缩。我 99.9% 确定内容没问题。
  • 缺少一些数据?您是如何验证这一点的?
  • md5sum 不同。然而,现在我已经在 QtCreator 中的工作和爱好会话之间切换,这重新初始化了项目,瞧,它正在工作。代码没有变化!大小和 md5sum 现在是一样的。解压例程 不明白。

标签: c++ qt qfile qbytearray


【解决方案1】:

我需要从文件中读取二进制数据

我对Qt没有太多经验,但是将大型二进制文件读入内存很容易,然后您可以将其传递给gzip进行解压缩。你可以试试这样的。使用像std::deque 这样的容器将文件存储在内存中,因为它很大并且不需要像std::vector 那样分配在连续空间中。

// set the chunk size to be the maximum I/O unit for your machine*
const size_t chunk_size = static_cast<size_t>(32768);
std::deque<uint8_t> bytes;  // store the whole file
std::vector<uint8_t> chunk(chunk_size, 0);  // temporary file chunk

std::ifstream dataFile;
dataFile.open( fileName.c_str(), std::ios::in | std::ios::binary );

if ( dataFile.is_open() )
{
    // read entire file large chunks at a time
    while ( dataFile.read(reinterpret_cast<char*>(&chunk[0]),
                          chunk.size()) ||
            dataFile.gcount() )
    {
        // append each chunk to our data store
        bytes.insert(bytes.end(),
                     chunk.begin(),
                     chunk.begin() + dataFile.gcount());
    }

    dataFile.close();  // close the file when we're done
}
else
{
    std::cerr << "Failed to create file stream on ->" << fileName << "<-" << std::endl;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2015-06-27
    • 2015-04-23
    • 2018-01-16
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2019-04-04
    相关资源
    最近更新 更多