首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >C++11/14中的高效文件读取

C++11/14中的高效文件读取
EN

Stack Overflow用户
提问于 2015-08-25 19:18:54
回答 1查看 7K关注 0票数 3

我正在创建一个IOManager类,其中我有一个函数来读取一个文件并将其存储在一个缓冲区中。这样做最有效的方法是什么?

我目前有2段代码:

代码语言:javascript
复制
bool IOManager::readFileToBuffer(std::string filePath, std::vector<unsigned char>& buffer) {
    std::ifstream file(filePath, std::ios::binary);
    if (file.fail()) {
        perror(filePath.c_str());
        return false;
    }

    //seek to the end
    file.seekg(0, std::ios::end);

    //Get the file size
    int fileSize = file.tellg();
    file.seekg(0, std::ios::beg);

    //Reduce the file size by any header bytes that might be present
    fileSize -= file.tellg();

    buffer.resize(fileSize);
    file.read((char *)&(buffer[0]), fileSize);
    file.close();

    return true;
}

代码语言:javascript
复制
bool IOManager::readFileToBuffer(std::string filePath, std::vector<char>& buffer) {

    std::ifstream file(filePath, std::ios::binary);

    if (file.fail()) {
        perror(filePath.c_str());
        return false;
    }

    // copies all data into buffer
    std::vector<char> prov(
        (std::istreambuf_iterator<char>(file)),
        (std::istreambuf_iterator<char>()));

    buffer = prov;

    file.close();

    return true;
}

哪一个更好?按照C++11/14标准,这是最快和最有效的方法吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-08-25 19:28:52

我希望第一个版本比第二个版本更快。它将是单个流调用,它将转换为单个(除非有信号)内核read()调用。

第二个版本现在有一个潜在的多个重分配的问题,但是这可以通过首先保留大小的向量,而不是从迭代器复制到它来解决。但更大的问题是,它将转换为多个调用来读取()函数。

票数 7
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32212255

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档