在线时间:8:00-16:00
迪恩网络APP
随时随地掌握行业动态
扫描二维码
关注迪恩网络微信公众号
其他参考: linux系统下的 C 编程,头文件相关;哪里找-> sys/types.h, sys/stat.h
命令行选项解析函数(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]); } }
|
2023-10-27
2022-08-15
2022-08-17
2022-09-23
2022-08-13
请发表评论