C++ 文件操作实例
图1 文件个数及名称
图2 文件内容
背景:如图1所示,现有9个要处理的文件,每个文件的内容格式如图2所示,仅仅只是数值部分不同。
问题:如何提取每个文件中的相同属性的数值到同一个文件中?
输出示例:如将ExpectedCalue属性的每个数值提取到另一个文件中,格式为
实现代码:
#include <stdlib.h> #include <fstream> #include<iostream> using namespace std; void GetNumber( char buf[], int order, char path[]) //截取数字(存放地址、位置、文件路径) { int start,end; ifstream file(path); for ( int i=1; i<=order; i++) { while (file.get() != '=' ); start = file.tellg(); //std::cout<<file.tellg()<<std::endl; while (file.get() != 'E' ); end = file.tellg(); //std::cout<<file.tellg()<<std::endl; } file.seekg(start+1); file.get(buf,end-start); file.close(); } void WriteToFile( char buf[], float xorder, char path[]) //截取数字(存放地址、位置、文件路径) { ofstream file(path,ios::app); file<<xorder<< "\t" <<buf<<std::endl; file.close(); } void main() { char ch; char *buf = new char [100]; char *FileName = new char [100]; char *address = new char [100]; float sum; for ( int i=1; i<=9; i++) { sum = 0; sprintf (FileName, "C:\\timenet\\models\\SYS.dir\\%.1f.RESULTS" ,0.5*i); std::cout<<FileName<<std::endl; for ( int j=1; j<=9; j++) { GetNumber(buf,j,FileName); std::cout<<buf<<std::endl; if (j == 1) { sprintf (address, "C:\\timenet\\models\\SYS.dir\\ExpectedValue.txt" ); WriteToFile(buf, 0.5*i, address); } else if (j == 3) { sprintf (address, "C:\\timenet\\models\\SYS.dir\\EVsleep.txt" ); WriteToFile(buf, 0.5*i, address); } else if (j == 4) { sprintf (address, "C:\\timenet\\models\\SYS.dir\\EVa2s.txt" ); WriteToFile(buf, 0.5*i, address); } else if (j == 5) { sprintf (address, "C:\\timenet\\models\\SYS.dir\\EVS2D.txt" ); WriteToFile(buf, 0.5*i, address); } else if (j == 9) { sprintf (address, "C:\\timenet\\models\\SYS.dir\\EVService.txt" ); WriteToFile(buf, 0.5*i, address); } } } delete []buf; delete []FileName; delete []address; system ( "pause" ); } |
【推荐】还在用 ECharts 开发大屏?试试这款永久免费的开源 BI 工具!
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步