C++ 读写文件,格式化输出到文件的简单代码

本文提供了一段C++代码示例,详细介绍了如何进行文件的读写操作,以及如何实现格式化的输出到文件。通过这段代码,开发者可以了解C++在文件操作方面的基本用法。


简单的读写文件的C++代码



//读文件一
string fileName;
std::ifstream inputFile(fileName.c_str());
if(!inputFile)
{
	std::cerr << "some errors happened"; 
	return NULL;    
}
inputFile.seekg(0, ios::end);      //设置文件指针到文件流的尾部
streampos ps = inputFile.tellg();  //读取文件指针的位置
cout << "File size(行): " << (ps/81) << endl;
int totalRow = ps/81;//每一行固定有81个字节
inputFile.seekg(0, ios::beg);      //重新设置文件指针到文件流的头部

const int MAX=90;
char lineBuffer[MAX];
while(inputFile.getline(lineBuffer,MAX))
{
	std::string readLineString(lineBuffer);
}
inputFile.close();



//读文件二
boost::filesystem::path fpath("./../InputConfig/StreamerConfig");
std::fstream filestream;
filestream.open( fpath.string().c_str());
if( !filestream.is_open() )
{
	std::cerr << "can't open file \"StreamerConfig\"" << std::endl;
	return false;
}
std::string strline;
while ( getline( filestream, strline ) )
{
}
filestream.close();



//写文件
boost::filesystem::path myPath("./../OutputConfig");
if( !( boost::filesystem::exists(myPath) && (boost::filesystem::is_directory(myPath)) ))
{
	// 创建目录OutputConfig
	if( boost::filesystem::create_directories( myPath ) )
	{
		std::cout << "create ./../OutputConfig success" << std::endl;
	}else
	{
		// 创建目录失败,退出
		std::cerr << "create ./../OutputConfig failed " << std::endl;
		return;
	}
}
boost::filesystem::path fpath_outputSurveyLine("./../OutputConfig/outputSurveyLine.txt");

/*
//无格式写文件
std::ofstream fout;
fout.open( fpath_outputSurveyLine.string().c_str() );
if(!fout.is_open())
{
	std::cout << "open file error." << std::endl;
	return;
}
fout<<"m_LineName:"<<m_LineName;
fout<<'\n';
fout<<"m_SeqNo:"<<m_SeqNo;
fout<<'\n';
fout.close();
*/

//有格式写文件,更多关于格式的参数可以百度printf函数的参数介绍
FILE* fout = fopen( fpath_outputSurveyLine.string().c_str(),"w+");
fprintf(fout,"%-10d",platId);//-表示左对齐,不加默认右对齐,10表示占10个字节,d表示输出整数
fprintf(fout,"%-14s",compass->getSerialNo().c_str());//s表示输出字符串
fprintf(fout,"%-15f",compass->getOffsetY());//f表示输出浮点数
fprintf(fout,"%-30s%-35s%-30s\n","LineName","Latitude","Longitude");
fclose(fout);







评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值