首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> C語言 >> C++ >> 關於C++

C++ 高效讀取整個文字檔至 string

     編輯:關於C++

最高效做法

  1. 以二進位模式開啟檔案(std::ios::binary)。
  2. seekg(0, end) 取得檔案大小。
  3. resize() 預分配字串空間。
  4. seekg(0, beg) 回到開頭。
  5. read(&str[0], size) 一次性讀入。

程式碼

/* main.cpp
 * Created on: 2014年6月17日
 * Author: Spike
 */
#include <iostream>
#include <fstream>
#include <string>
#include <cerrno>

std::string get_file_contents(const char* filename) {
    std::ifstream in(filename, std::ios::in | std::ios::binary);
    if (in) {
        std::string contents;
        in.seekg(0, std::ios::end);
        contents.resize(in.tellg());
        in.seekg(0, std::ios::beg);
        in.read(&contents[0], contents.size());
        in.close();
        return contents;
    }
    throw(errno);
}

int main() {
    cout << get_file_contents("跳河的兔子.txt") << endl;
    return 0;
}

為何高效

  • 避免逐行讀取的多次配置與複製。
  • 單次系統呼叫 read 將資料直接搬入字串緩衝區。
  • 二進位模式避免換行符轉換開銷。

注意

  • C++11 保證 string 連續儲存,&contents[0] 安全。
  • 超大檔案(> 記憶體)請改用記憶體映射檔(mmap/CreateFileMapping)。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved