• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

C语言实现Linuxtouch命令

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

参考教程:C 语言实现 Linux touch 命令

其他参考:

C语言动态变量和静态变量的区别

linux系统下的 C 编程,头文件相关;哪里找-> sys/types.h, sys/stat.h

parameter和argument的区别

 

命令行选项解析函数(C语言):getopt()和getopt_long()  (学习getopt()函数即可) 

getopt函数 (配合学习,适合最后看,学习完本教程后,再看基本就能理解)

 

代码:(相比教程中少用了头文件 和 修改函数返回值为ok)

#include <unistd.h>
#include <getopt.h>
#include <fcntl.h>
#include <sys/stat.h>

#include <stdbool.h>
#include <stdlib.h>

#define CH_ATIME 1
#define CH_MTIME 2

#define MODE_RW_UGO (S_IRUSR | S_IWUSR | S_IRGRP | S_IWGRP | S_IROTH | S_IWOTH)

// acess time and modify time
static int change_times;
// -c
static bool no_create;
// new a/m time
static struct timespec newtime[2];

static bool mytouch(const char *file)
{
    bool ok;
    int fd = -1;
    if ( no_create != 1)
        fd = open(file, O_CREAT | O_WRONLY, MODE_RW_UGO);

    if (change_times != (CH_ATIME | CH_MTIME))
    {
        if (change_times == CH_ATIME)
            newtime[1].tv_nsec = UTIME_OMIT;
        else
            newtime[0].tv_nsec = UTIME_OMIT;
    }
    ok = (utimensat(AT_FDCWD, file,  newtime, 0) == 0);
    return ok;
}

int main(int argc, char **argv)
{
    int c;
    bool ok = true;

    no_create = false;
    change_times = 0;

    while ((c = getopt(argc, argv, "acm")) != -1)
    {
        switch (c)
        {
        case 'a':
            change_times |=  CH_ATIME;
            break;

        case 'c':
            no_create = true;
            break;

        case 'm':
            change_times |= CH_MTIME;
            break;

        default:
            printf("fault option!");
        }
    }    

    if (change_times == 0)
        change_times = CH_ATIME | CH_MTIME;
    
    newtime[0].tv_nsec = UTIME_NOW;
    newtime[1].tv_nsec = UTIME_NOW;

    if (argc == optind)
        printf("missing file operand\n");

    for (; optind < argc; ++optind)
        ok &= mytouch(argv[optind]);

    exit(ok ? EXIT_SUCCESS : EXIT_FAILURE);    
}

使用教程中的例子测试:

./mytouch shiyanlou
stat shiyanlou

 

 

附上之前的学习代码:

#include <stdio.h>
#include <unistd.h>
#include <getopt.h>

int main(int argc, char **argv){
    int opt;
    char *optstring = "a::b:c::d";
    while((opt = getopt(argc, argv, optstring)) != -1){
        printf("opt = %c\t\t", opt);
        printf("optarg = %s\t\t", optarg);
        printf("optind = %d\t\t", optind);
        printf("argv[optind] = %s\n", argv[optind]);
    }
}

 


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
C#预处理器指令发布时间:2022-07-13
下一篇:
C#winform中ListView用法发布时间:2022-07-13
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap