1 头文件

#include

#include

#include


2 读取一行

void ReadLineByifstream()
{
 char szBuffer[2560] = { 0 };
 std::ifstream  fileHandle("F:/ffmpeg/file/32497272.h264", std::ifstream::in | std::ifstream::binary);
 fileHandle.getline(szBuffer, 2560);
 size_t nLen = strlen(szBuffer);
 std::cout << nLen << std::endl;
 fileHandle.close();

}

注意:getline函数读取到0的时候,也会成功返回,例如现在读取的文件是一个视频文件,文件的开头三个字节都是0,所以读取到的szBuffer都是空


3 读取整个文本

void ReadWholeFileByifstream()
{
 std::ifstream  fileHandle("F:/ffmpeg/file/32497272.h264", std::ifstream::in | std::ifstream::binary);
 fileHandle.seekg(0, std::ios::end);
 int nFileLen = fileHandle.tellg();
 fileHandle.seekg(0, std::ios::beg);
 char* pFileBuf = new char[nFileLen];
 fileHandle.read(pFileBuf, nFileLen);
 std::cout << nFileLen << std::endl;
 delete pFileBuf;
 fileHandle.close();
}

注意:std::ifstream::in | std::ifstream::binary必不可少,否则读取文件不完整


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

void UsingifstreamReadJson()

{

 std::ifstream  fileHandle("F:/ffmpeg/file/32497272.h264", std::ifstream::in | std::ifstream::binary);


Json::Reader reader;

Json::Value root;

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

{

fileHandle.close();

return;

}


fileHandle.close();

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

}