1 头文件
#include
#include
#include
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
#include
#include
std::ifstream t("file.txt");
std::string str((std::istreambuf_iterator
std::istreambuf_iterator
第二种方法:
#include
#include
#include
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