c++中ifstream一次读取整个文件

c++中一次读取整个文件的内容的方法:

1. 读取至char*的情况

[cpp]  view plain copy
  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的情况

第一种方法:

[cpp]  view plain copy
  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>());  

第二种方法:

[cpp]  view plain copy
  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

本文出自 夜惊心的博客 ,转载请保留出处

你可能感兴趣的:(C++)