gpt4 book ai didi

在 UNIX 中创建自定义选项

转载 作者:行者123 更新时间:2023-11-30 14:48:59 25 4
gpt4 key购买 nike

我想使用 c 文件在 cat 中创建新选项

我是 Unix 新手,所以我不知道该使用什么。

我要编译

./mycat -s 16 foo 

16 是缓冲区大小,foo 是文件名

使用 mycat.c 文件和代码如下

#include <stdio.h> /* fprintf */
#include <unistd.h> /* getopt */
#include <stdlib.h> /* exit */

/* debug mode (-d option) */
int is_debug = 0;

/* prints log message to stderr only when -d is available */
#define LOG(fmt, ...) do { if (is_debug) fprintf(stderr, fmt "\n", __VA_ARGS__); } while (0)


/* Non-portable functions for checking stdio's buffer size, etc. */

/* checks if the given stream is line-buffered */
int is_stdio_linebuffered(FILE *stream) {
return (stream->_flags & __SLBF) > 0;
}

/* checks if the given stream is NOT buffered */
int is_stdio_unbuffered(FILE *stream) {
return (stream->_flags & __SNBF) > 0;
}

/* obtains the buffer size of the given stream */
int stdio_buffer_size(FILE *stream) {
return stream->_bf._size;
}

int main(int argc, char **argv) {
int opt, i;
while ((opt = getopt(argc, argv, "dm:")) != -1) {
switch (opt) {
case 'd':
is_debug = 1;
break;
case 'm':
fprintf(stderr, "%s: message is '%s'\n", argv[0], optarg);
break;
case 'i': ???????????????????????????????????
default:
fprintf(stderr, "Usage: %s [-d] [-m message] args...\n", argv[0]);
exit(EXIT_FAILURE);
}
}

for (i = optind; i < argc; i++) {
LOG("[%d] %s", i, argv[i]);
}
return 0;
}

so c文件需要添加一些代码

但我不知道该使用什么功能

如何设置 -i 选项来获取缓冲区大小和文件名?

最佳答案

getopt() 的签名是

int getopt(int argc, char * const argv[], const char *optstring);

optstring中,必须指定选项字符。仅当选项字符始终需要参数时,选项字符后才会跟一个 :。两个分号用于可选参数,而对于始终没有参数的参数则不使用分号。

您需要一个带有整数参数的选项-s

在使用 getopt() 时,还有另外两个选项 dm 不带参数(我假设m 并不像您想要的那样接受参数 ./mycat -s 16 foo 进行编译。如果您愿意,请将其更改为接受可选参数。

所以getopt()应该是

while ((opt = getopt(argc, argv, "dms:")) != -1) {
....
....
}

switch 语句的 case 's':

case 's': 
iopt = strtol(optarg, &dp, 10);
if(iopt==0 && errno == ERANGE)
{
errno = 0;
perror("Number out of range");
}
else if(*dp != 0)
{
printf("\nNot a numeric value. Non number part found");
}
break;

optarg 将指向字符串的开头,该字符串是 s 选项的参数。

由于我们需要它作为数字,因此您需要将字符串转换为数字。

strtol() 用于此目的。如果成功,它会返回 long 类型的数字。
如果数字太大而无法包含在long中,则返回0并将errno设置为ERANGE。要检查这些错误代码,您必须包含 errno.h

您可以使用与 strtol() 同族的其他函数来获取其他类型的值。例如:strtoll() 表示 long long

关于在 UNIX 中创建自定义选项,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50084345/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com