文件操作——日期排序

#include <iostream>
#include <stdlib.h>

#include <stdio.h>
#include <vector>
using namespace std;
#define MAXLINELENGTH 20
#define YEAR 1970
typedef struct DATE
{
 int year;
 int month;
 int day;
 int hour;
 int min;
 int sec;
} DATE;

/*儲存12個月的天數*/
const int days[12]={31,28,31,30,31,30,31,31,30,31,30,31};

/*判斷是否爲閏年*/
int isLeapYear(int year)
{
 if(((year%4==0)&&(year%100!=0))
    ||(year%400==0))
 {
  return 1;
 }
 return 0;
}

long date2sec(DATE d)
{
    /*日期轉成1970年1月1日起的天數*/

    long sum=0;
    int i;

    //累計以往各年的天數
    for(i=YEAR;i<d.year;i++)
    {
        sum+=365;
        if(isLeapYear(i))
        {//閏年多一天
            sum+=1;
        }
    }
    //累計當年以往各月的天數
    for(i=0;i<d.month;i++)
    {
        sum+=days[i];
    }
    if(d.month>2)
    {
        if(isLeapYear(i))
        {//閏年多一天
            sum+=1;
        }
    }
    //累計當年當月的天數
    sum+=d.day-1;
    //轉換成秒
    sum=sum*24*60*60;

    //加當天的小時,分鐘,秒
    sum+=d.hour*60*60+d.min*60+d.sec;
    //返回總秒數
    return sum;
}



void sortdate()
{
    FILE *fpin,*fpout;

    char *infile  = "../testcase/datein.txt";
    char *outfile = "../testcase/dateout.txt";
    fpin          = fopen(infile,"r");
    fpout         = fopen(outfile,"w");
    char buffer[MAXLINELENGTH]={'\0'};
    vector<string> lines ;
    vector<long> linesec;
    while(fgets(buffer,MAXLINELENGTH,fpin))
    {
        lines.push_back(buffer);
        string temp(buffer);
        string moth(temp.begin(),temp.begin()+2);
        string day(temp.begin()+3,temp.begin()+5);
        string year(temp.begin()+6,temp.begin()+10);
        int m = atoi(moth.c_str());
        int d = atoi(day.c_str());
        int y = atoi(year.c_str());
        DATE dat;
        dat.day=d;
        dat.month = m;
        dat.year = y;
        dat.hour = 0;
        dat.min  = 0;
        dat.sec  = 0;
        linesec.push_back(date2sec(dat));
    }
    //排序
    for(int i = 0;i<lines.size();i++)
    {
        for(int j = i+1;j<lines.size();j++)
        {
            if(linesec[i]>linesec[j])
            {
                long tmp = linesec[i];
                string tmpstr = lines[i];
                linesec[i]=linesec[j];
                lines[i]=lines[j];
                linesec[j]=tmp;
                lines[j]=tmpstr;
            }
        }
    }
    //寫入文件
    int idx =0;
   while(idx<lines.size())
   {
       fprintf(fpout,"%s",lines[idx].c_str());
       idx++;
   }

   fclose(fpin);
   fclose(fpout);

}


int main()
{
    sortdate();
    cout << "Hello World!" << endl;
    return 0;
}

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章