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

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

1. 讀取至char*的情況

  1. std::ifstream t;  
  2. int length;  
  3. t.open("file.txt");      // open input file  
  4. t.seekg(0, std::ios::end);    // go to the end  
  5. length = t.tellg();           // report location (this is the length)  
  6. t.seekg(0, std::ios::beg);    // go back to the beginning  
  7. buffer = new char[length];    // allocate memory for a buffer of appropriate dimension  
  8. t.read(buffer, length);       // read the whole file into the buffer  
  9. t.close();                    // close file handle  
  10.   
  11. // ... do stuff with buffer here ...  

2. 讀取至std::string的情況

第一種方法:

  1. #include <string>  
  2. #include <fstream>  
  3. #include <streambuf>  
  4.   
  5. std::ifstream t("file.txt");  
  6. std::string str((std::istreambuf_iterator<char>(t)),  
  7.                  std::istreambuf_iterator<char>());  

第二種方法:

  1. #include <string>  
  2. #include <fstream>  
  3. #include <sstream>  
  4. std::ifstream t("file.txt");  
  5. std::stringstream buffer;  
  6. buffer << t.rdbuf();  
  7. std::string contents(buffer.str());  

reference: http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章