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


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章