【发布时间】: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。 -
检查输出是否被缓冲的函数正在执行完全相同的事情并获得相同的结果可能不是您想要的。