C 语言实现 Linux touch 命令

参考教程: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]);
    }
}

 

转载于:https://www.cnblogs.com/exciting/p/11018394.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值