c++中ifstream一次讀取整個文件


c++中一次讀取整個文件的內容的方法:

  1. 讀取至char*的情況
std::ifstream t; int length; t.open("file.txt"); // open input file t.seekg(0, std::ios::end); // go to the end length = t.tellg(); // report location (this is the length) t.seekg(0, std::ios::beg); // go back to the beginning buffer = new char[length]; // allocate memory for a buffer of appropriate dimension t.read(buffer, length); // read the whole file into the buffer t.close(); // close file handle // ... do stuff with buffer here ... 
  1. 讀取至std::string的情況:

第一種方法:

#include <string> #include <fstream> #include <streambuf> std::ifstream t("file.txt"); std::string str((std::istreambuf_iterator<char>(t)), std::istreambuf_iterator<char>()); 

第二種方法:

#include <string> #include <fstream> #include <sstream> std::ifstream t("file.txt"); std::stringstream buffer; buffer << t.rdbuf(); std::string contents(buffer.str()); 

reference

http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring

本文出自夜驚心的博客,轉載請保留出處


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM