C++读写文本文件和二进制文件

  • Post author:
  • Post category:其他


写文本文件:

#include <fstream>
void SaveFileTxt(string jsonStr)
{
	ofstream ofile(m_filename, std::ofstream::out);
	if (!ofile)
	{
		LOG(ERR, "open file error");
		return;
	}
	ofile << jsonStr;
	ofile.close();

}

读文本文件:

string LoadFromFileTxt()
{
	ifstream ifile(m_filename);
	if (!ifile)
	{
		LOG(ERR, "open file error");
		return "";
	}
	//将文件读入到ostringstream对象buf中
	ostringstream buf;
	char ch;
	while (buf && ifile.get(ch))
		buf.put(ch);

	ifile.close();
	string outStr = buf.str();
	LOG(INF, "readStr = [%s]", outStr.c_str());
	//返回与流对象buf关联的字符串
	return outStr;
}

写二进制文件:

void SaveToFileBinary(string jsonStr)
{
	
	//写出数据
	ofstream ofile(m_filename, ios::binary);
	if (!ofile)
	{
		LOG(ERR,"open file error");
		return;
	}
	ofile.write((char*)jsonStr.c_str(), jsonStr.length());
	
	ofile.close();

}

读二进制文件:

string LoadFromFileBinary()
{
	
	ifstream ifile(m_filename,ios::binary);
	if(!ifile)
	{
		LOG(ERR, "open file error");
		return "";
	}
	std::vector<char> vecText;
	ifile.seekg(0, ios_base::end);
	long long fileSize = ifile.tellg();
	ifile.seekg(0, ios_base::beg);
	char tmp;
	
	for (long i = 0; i < fileSize; i++)
	{
		ifile.read(&tmp,1);
		vecText.push_back(tmp);
	}
	
	ifile.close();
	string outStr = "";
	
	outStr.assign(vecText.begin(), vecText.end());
	//LOG(INF, "readStr = [%s]", outStr.c_str());
	//返回与流对象buf关联的字符串
	return outStr;
	
	//return "";
}



版权声明:本文为lizfs_csdn原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。