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]);
    }
}

 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM