【问题标题】:creating custom options in unix在 unix 中创建自定义选项
【发布时间】:2018-04-29 07:31:39
【问题描述】:

我想使用 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;
}

所以c文件需要添加一些代码

但是不知道用什么函数

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

【问题讨论】:

  • 也许从阅读getopt()的文档开始?为此,请运行 man getopt
  • 检查输出是否被缓冲的函数正在执行完全相同的事情并获得相同的结果可能不是您想要的。

标签: c unix getopt


【解决方案1】:

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) {
    ....
    ....
} 

case 's':switch 声明中

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-12-14
    • 1970-01-01
    • 2013-04-13
    • 1970-01-01
    • 1970-01-01
    • 2017-03-17
    • 2016-06-29
    • 2021-10-10
    相关资源
    最近更新 更多