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

  

转载于:https://www.cnblogs.com/whl2012/p/3261913.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值