您的位置:首页 > 编程语言 > C语言/C++

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

2015-01-13 16:38 483 查看
简单的读写文件的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);
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: