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");
}

  

posted on 2013-08-17 08:29  whl-hl  阅读(520)  评论(0编辑  收藏  举报

导航