std::ifstream 读取文件

1 头文件

#include <iostream>

#include <fstream>

#include <string>


2 读取一行

void UsingifstreamReadLineMethod()

{

char szBuf[256] = { 0 };

std::ifstream  fileHandle("E:/thriftserver/output/facealarmnew.txt");

fileHandle.getline(szBuf, 100);

size_t nLen = strlen(szBuf);

}


3 读取整个文本

void UsingifstreamReadMethod1()

{

std::ifstream fileHandle;

int nFileLen = 0;

fileHandle.open("E:/thriftserver/output/facealarmnew.txt");

fileHandle.seekg(0, std::ios::end);

nFileLen = fileHandle.tellg();

fileHandle.seekg(0, std::ios::beg);

char szFileBuf[4096] = { 0 };

fileHandle.read(szFileBuf, nFileLen);

std::cout << nFileLen << std::endl;

fileHandle.close();

}


void UsingifStreamReadMethod2()

{

std::ifstream fileHandle;

fileHandle.open("E:/thriftserver/output/facealarmnew.txt");

std::string strFileBuf;

fileHandle >> strFileBuf;

std::cout << strFileBuf.length() << std::endl;

}


上述的两个方法,都尝试读取整个文本的数据,但是第二个方法在读取Json格式的数据情况下,会出现读取不完整的情况,文本长度是2876,但是第二个方法读取到的字符串长度是871,所以在使用的过程中,一定要谨慎小心,目前怀疑是在读取到空字符的时候,就直接返回了,导致数据读取出错


4直接将ifstream文件句柄传递给Jsoncpp解析器,进行文本的解析

void UsingifstreamReadJson()

{

std::ifstream fileHandle;

fileHandle.open("E:/thriftserver/output/facealarmnew.txt");


Json::Reader reader;

Json::Value root;

if (NULL == reader.parse(fileHandle, root))

{

fileHandle.close();

return;

}


fileHandle.close();

std::string strName = root["name"].asString();

}


参考文章备忘


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


读取至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 ...  

读取至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());

reference


http://stackoverflow.com/questions/2602013/read-whole-ascii-file-into-c-stdstring


摘自:http://www.cnblogs.com/kex1n/p/4028428.html




     本文转自fengyuzaitu 51CTO博客,原文链接:http://blog.51cto.com/fengyuzaitu/1570348,如需转载请自行联系原作者

  • 3
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值