
现在才开始学C语言,开始学Linux下C编程,好像的确是挺晚的了。但总比现在还没开始要好吧。
下面是我根据《Beginning Linux Programming》第四版上gmtime例子,结合之前在这本书上学习的东西,改写了一个gmtime_my。嗯,现在我就这个水平。
放上源代码。
| #include <time.h> #include <stdio.h> #include <unistd.h> #include <stdlib.h> #define _GNU_SOURCE #include <getopt.h> void showhelp(){ printf("这个程序可以显示当前时间,或者通过指名时区显示某个时区的当前时间\n"); printf("用法:gmtime_my [选项]\n"); printf("选项:\n"); printf(" --timezone=[时区] : 指定要显示的时区\n"); printf(" -z [时区] : 指定要显示的时区\n"); printf(" --help : 显示本帮助\n"); printf(" -h : 显示本帮助\n"); } int main(int argc, char *argv[]){ int opt; struct option longopts[] = { {"timezone", 1, NULL, 'z'}, {"help", 0, NULL, 'h'}, {0,0,0,0} }; int timezone = 0; char *timezonez = "+0"; short int settimezone = 0; while((opt = getopt_long(argc, argv, ":z:h", longopts, NULL)) != -1){ if(opt == 'z'){ timezone = atoi(optarg); //这个是把字符串转换成整数的函数 timezonez = optarg; settimezone = 1; if(timezone < -12 || timezone > 12){ printf("时区是在-12到12之间的整数,而不是%s\n", optarg); exit(0); } }else if(opt == 'h'){ showhelp(); exit(0); }else if(opt == '?'){ showhelp(); exit(0); } } struct tm *tm_ptr; time_t the_time; (void) time(&the_time); if(settimezone == 0){ tm_ptr = localtime(&the_time); }else{ the_time += (3600 * timezone); tm_ptr = gmtime(&the_time); } if(settimezone == 1){ printf("时区是: %s\n", timezonez); } printf("目前的日期时间为:\n"); printf(" 日期: %02d年%02d月%02d日\n", 1900+tm_ptr->tm_year, tm_ptr->tm_mon+1, tm_ptr->tm_mday); printf(" 时间: %02d:%02d:%02d\n", tm_ptr->tm_hour, tm_ptr->tm_min, tm_ptr->tm_sec); exit(0); } |
再放上点截图玩玩?


