#include <stdio.h> #include <stdlib.h> #include <string.h> #define ARGC_NUM 3 #define MAX_STR_NUM 6 #define H_AND_M_NUM 3 #define DELIMS ":" #define M_2_S 60 #define D_2_H 24*M_2_S int findH_M(char*str, char*h, char*m) { char* pTmp=NULL; int ulTmp=0; pTmp=strtok(str, DELIMS); ulTmp=strlen(pTmp); if (ulTmp>=H_AND_M_NUM) { printf("Error arg: %s\n", str); return -1; } memcpy(h, pTmp, ulTmp); pTmp=strtok(NULL, DELIMS); ulTmp=strlen(pTmp); if (ulTmp>=H_AND_M_NUM) { printf("Error arg: %s\n", str); return -1; } memcpy(m, pTmp, ulTmp); return 0; } /* 只支持24小时以内的时钟减法 */ int main(int argc, char* argv[]) { char strBegin[MAX_STR_NUM]=""; char strEnd[MAX_STR_NUM]=""; char BeginH[H_AND_M_NUM]=""; char BeginM[H_AND_M_NUM]=""; char EndH[H_AND_M_NUM]=""; char EndM[H_AND_M_NUM]=""; unsigned int ulBeginTimeM=0; unsigned int ulEndTimeM=0; int BeginLen=0; int EndLen=0; if (0 == strcmp("-h", argv[1])) { printf("Useage: calcTime BeginTime EndTime \n""e.g. calcTime 18:58 19:59\n"); return 0; } if (ARGC_NUM != argc) { printf("Error! argc=%d\n", argc); return -1; } BeginLen=strlen(argv[1]); EndLen=strlen(argv[2]); if ((BeginLen>=MAX_STR_NUM) || (EndLen>=MAX_STR_NUM)) { printf("Error len! argv[1]=%s, argv[2]=%s\n", argv[1], argv[2]); return -1; } memcpy(strBegin, argv[1], BeginLen); memcpy(strEnd, argv[2], EndLen); if ((0 != findH_M(strBegin, BeginH, BeginM)) || (0 != findH_M(strEnd, EndH, EndM))) { return -1; } ulBeginTimeM=atoi(BeginH)*M_2_S+atoi(BeginM); ulEndTimeM=atoi(EndH)*M_2_S+atoi(EndM); ulEndTimeM=(ulEndTimeM>ulBeginTimeM)?(ulEndTimeM):(ulEndTimeM+D_2_H); printf("Congratulations! End-Begin is %d:%d\n", (ulEndTimeM-ulBeginTimeM)/M_2_S,(ulEndTimeM-ulBeginTimeM)%M_2_S); return 0; }
使用方法:
X:\gcc>calcTime -h
Useage: calcTime BeginTime EndTime
e.g. calcTime
18:58 19:59
X:\gcc> calcTime 18:58 19:59
Congratulations! End-Begin is 1:1
原文:http://www.cnblogs.com/caixu/p/3631970.html