简单的读写文件的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);
本文提供了一段C++代码示例,详细介绍了如何进行文件的读写操作,以及如何实现格式化的输出到文件。通过这段代码,开发者可以了解C++在文件操作方面的基本用法。
3万+

被折叠的 条评论
为什么被折叠?



