警告
警告内容
确定
内容是加密的,请输入密码

确定
首页 >> Blog >> 学习实验的C程序  [Go back. ^_^]
学习实验的C程序
1278905123 栏目:开发者 作者:火志溟 浏览() 评论()

    现在才开始学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);
}

 

    再放上点截图玩玩?

本文章内容遵循署名-非商业性使用-禁止演绎创作共用协议   Tags: C语言  Linux  
[评论内容的所有权利属于评论者,并且只代表评论者的个人观点,与本网站无关。]
姓名:
 
输入您想显示的姓名
E-Mail:
 
不会公开显示,请放心。如果有必要网站管理者将用此与您取得联系。
评论内容:

忆黛蒙逝·博[from百度空间(停用)]    瑞丽服饰潮流馆[朋友的淘宝店]    我的新浪微博

Creative Commons License
忆黛蒙逝·建造源
鲁ICP备05000493号