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:"<getSerialNo().c_str());//s表示输出字符串
fprintf(fout,"%-15f",compass->getOffsetY());//f表示输出浮点数
fprintf(fout,"%-30s%-35s%-30s\n","LineName","Latitude","Longitude");
fclose(fout);







你可能感兴趣的:(c++)