c++中ifstream一次读取整个文件
2013-06-06 11:37
585 查看
http://blog.csdn.net/tulip527/article/details/7976471
http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
c++中一次读取整个文件的内容的方法:
1. 读取至char*的情况
2. 读取至std::string的情况
第一种方法:
第二种方法:
#include <string>
#include <fstream>
#include <sstream>
std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();
std::string contents(buffer.str());
http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring
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 ...
2. 读取至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());
相关文章推荐
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++中ifstream一次读取整个文件
- c++使用getline和ifstream读取文件
- C++中利用文件输入对象(即ifstream对象)来读取文本文件中带空格的字符串以及混合输入数字与字符串
- 转自【北漂民工】C++文件读取操作的全部函数讲解fstream(ofstream/ifstream)
- ifstream(一)之 eof() 函数——解决读取文件最后一个数据多读一次的方法
- C++ 读取配置文件的 ofstream和ifstream详细用法
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- c++使用getline和ifstream读取文件
- C++fstream,ifstream和outstream读取文件最后一行注意
- C++读取写入.txt文件(ifstream/ofstream)—读取指定行,修改指定行,复制文件,清除文件,统计文件行数
- c++ std::ifstream 读取文件不完整? 是不是忘记了ios_base::binary
- C++文件读写详解(ofstream,ifstream,fstream)
- C++文件读写详解(ofstream,ifstream,fstream)
- 【转】C++文件读写详解(ofstream,ifstream,fstream)