登录    注册      
    
  

News Message

c++中ifstream一次读取文件



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   
#include   
#include   
  
std::ifstream t("file.txt");  
std::string str((std::istreambuf_iterator<char>(t)),  
                 std::istreambuf_iterator<char>()); 

第二种方法:

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



Share Http URL:  http://www.wittx.cn/get_news_message.do?new_id=776



请输入评论





























Best Last Month

证监会同意5家公司创业板IPO

证监会同意5家公司创业板IPO

Information industry

by wittx


软银再向WeWork输血11亿美元

软银再向WeWork输血11亿美元

Information industry

by wittx


随机优化算法的证明以及在架构搜索上的应用



金属材料重要突破进展汇总

金属材料重要突破进展汇总

Information industry

by wittx


集成电路

集成电路

Computer software and hardware

by wittx


FaceBook时间管理

FaceBook时间管理

Office culture and education

by wittx


纳指收涨 1%,特斯拉、苹果、Zoom 创新高,黄金股上涨



今年最大并购!估值 440 亿美元,标普就收购 IHS Markit 达成最终协议



石墨烯实现超级电容电池

石墨烯实现超级电容电池

Electronic electrician

by wittx


波士顿动力第一款商用产品

波士顿动力第一款商用产品

Information industry

by wittx