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);
相关文章推荐
- 练习写C++代码(101)--简单的文件以及 .gz文件的读写
- c++ 文件读写简单示例
- ini文件纯C++读写代码
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++读写文件代码自动生成器(python3完成)
- 简单C++文件读写例子
- ini文件纯C++读写代码
- C++ 简单文件读写
- PHP的输出格式化与文件简单处理
- C++ 结合 Boost:40行代码读写和处理 txt 文件
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C/C++读写文件时莫忘了设置区域代码
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++的格式化输出(代码例子)
- ini文件纯C++读写代码
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组 (转)
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++ 文件读写 字符输出 字符串输出
- c++简单读写文本,统计文件的行数,读取文件数据到数组
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组