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   whl-hl  阅读(534)  评论(0编辑  收藏  举报

导航

< 2025年3月 >
23 24 25 26 27 28 1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 19 20 21 22
23 24 25 26 27 28 29
30 31 1 2 3 4 5
点击右上角即可分享
微信分享提示