//链表的应用:计算每个作业的运行时间 #include<stdio.h> #include<string.h> struct Task{ char name[50]; char sDate[15]; char sTime[15]; char eDate[15]; char eTime[15]; int cost; Task *next; }; struct Resource{ char ID[50]; Task *fstTask; Task *lstTask; Resource *next; }; int daysInMon[12]={31,28,31,30,31,30,31,31,30,31,30,31}; void computeTimeCost(Task *task){ int sYear,sMon,sDay,sHour,sMin,sSec; int eYear,eMon,eDay,eHour,eMin,eSec; int sDays=0,sSeconds; int eDays=0,eSeconds; int i; sscanf(task->sDate,"%d-%d-%d",&sYear,&sMon,&sDay); sscanf(task->sTime,"%d:%d:%d",&sHour,&sMin,&sSec); for(i=1;i<sMon;i++) sDays=sDays+daysInMon[i-1]; sDays=sDay-1; sSeconds=((sDays*24+sHour)*60+sMin)*60+sSec; sscanf(task->eDate,"%d-%d-%d",&eYear,&eMon,&eDay); sscanf(task->eTime,"%d:%d:%d",&eHour,&eMin,&eSec); for(i=1;i<eMon;i++) eDays=eDays+daysInMon[i-1]; eDays=eDays-1; eSeconds=((eDays*24+eHour)*60+eMin)*60+eSec; task->cost=(eYear-sYear)*365*24*3600-sSeconds+eSeconds; } Resource *processLog(char log[],Resource *resList){ char date[30],time[30],taskName[30]; Resource *curRes,*temp; Task *curTask; if(strstr(log,"created")){ curRes=new Resource; curRes->fstTask=curRes->lstTask=NULL; sscanf(strstr(log,"created")+9,"%s",curRes->ID); curRes->next=NULL; if(resList==NULL) return curRes; temp=resList; while(temp->next!=NULL) temp=temp->next; temp->next=curRes; return resList; } sscanf(log,"%s%s%s",date,time,taskName); curRes=resList; while(strstr(log,curRes->ID)==NULL) curRes=curRes->next; if(strstr(log,"started")){ curTask=new Task; strcpy(curTask->name,taskName); strcpy(curTask->sDate,date); strcpy(curTask->sTime,time); curTask->next=NULL; if(curRes->fstTask==NULL) curRes->fstTask=curTask; else curRes->lstTask->next=curTask; curRes->lstTask=curTask; } if(strstr(log,"finished")){ curTask=curRes->fstTask; while(strcmp(curTask->name,taskName)!=0) curTask=curTask->next; strcpy(curTask->eDate,date); strcpy(curTask->eTime,time); computeTimeCost(curTask); } return resList; } int main() { FILE *fin,*fout; char log[80],logFile[30],resultFile[30]; Resource *resList,*curRes; Task *task; printf("input log file's name: "); scanf("%s",logFile); printf("input the file name for saving results "); scanf("%s",resultFile); resList=NULL; fin=fopen(logFile,"r"); fgets(log,80,fin); while(strlen(log)>1){ resList=processLog(log,resList); fgets(log,80,fin); if(feof(fin)) break; } fclose(fin); fout=fopen(resultFile,"w"); while(resList!=NULL){ curRes=resList; resList=curRes->next; sprintf(log,"Tasks performed on resource %s ",curRes->ID); fputs(log,fout); while(curRes->fstTask!=NULL){ task=curRes->fstTask; curRes->fstTask=task->next; sprintf(log,"%s%10s%8d(s)%15s ",task->sDate,task->sTime,task->cost,task->name); fputs(log,fout); delete task; } fputs(" ",fout); delete curRes; } fclose(fout); return 0; }