一次性将文件从磁盘中读取到指定变量

方法1:

读取至std::string

代码1:istreambuf_iterator

《Effective STL》的源用法:

#include <string>
#include <fstream>
#include <streambuf>

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

代码2:stringstream

注意:
流插入<<和流提取>>操作符,通过重载,不仅具有格式化输入和输出的功能,还
Formatted IO operations are supported via overloading the stream insertion (<<) and stream extraction (>>) operators, which presents a consistent public IO interface.
在ostream类中通过对流插入操作符<<的重载实现格式化的输出。可以将数值化的值如int,double,将其从内部的表示方式,如16bit或者32bit等转为流格式。【convert numeric values (such as int, double) from their internal representations (e.g., 16-/32-bit int, 64-bit double) to a stream of characters that representing the numeric values in text form。】其未格式化的输出为put和write函数。【unformatted output functions (e.g., put(), write()) outputs the bytes as they are, without format conversion】

#include <string>
#include <fstream>
#include <sstream>

std::ifstream t("file.txt");
std::stringstream buffer;
buffer << t.rdbuf();//其中的<<操作符是逐个字符进行读取的
std::string contents(buffer.str());

同时,我们也可以用ifstream的read方法来进行数据的读取,再设置stringstream buffer 指向read的时候预先分配好的内存。如方法2所示:

方法2:ifstream .read()

读取到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
std::stringstream localStream;
localStream.rdbuf()->pubsetbuf(buffer,length);
string str3(localStream.str());
t.close(); // close file handle
//大家可以尝试下如果省略了localStream,而是直接string str3(buffer)对比下结果。相同吗?什么情况下相同,什么情况下又是不同呢?
// ... do stuff with buffer here ...

http://www.cnblogs.com/zhangzhang/archive/2012/05/07/2488825.html
http://www3.ntu.edu.sg/home/ehchua/programming/cpp/cp10_io.html
http://www.cplusplus.com/reference/istream/istream/read/
http://stackoverflow.com/questions/132358/how-to-read-file-content-into-istringstream

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值