加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-16 09:58:53 所属栏目:百科 来源:网络整理
导读:我正在创建一个IOManager类,其中我有一个函数来读取文件并将其存储在缓冲区中.这样做最有效的方法是什么? 我目前有2段代码: bool IOManager::readFileToBuffer(std::string filePath,std::vectorunsigned char buffer) { std::ifstream file(filePath,std:
我正在创建一个IOManager类,其中我有一个函数来读取文件并将其存储在缓冲区中.这样做最有效的方法是什么?

我目前有2段代码:

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;
}

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标准,这是最快速,最有效的方法吗?

解决方法

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读