删除C.c
#include <stdio.h>
int main(int argc, char **argv) {
if (argc != 2) {
int c;
while((c = getchar()) != EOF) {
if(c != 'c') {
putchar(c);
}
}
} else {
for (size_t i = 0; argv[1][i] != '\0'; i++) {
if(argv[1][i] != 'c') {
putchar(argv[1][i]);
}
}
putchar('\n');
}
}
removeC.c 删除文件中的每个 c 然后将其打印到标准输出。例如,
$ gcc -Wall removeC.c
$ ./a.out abc
ab
$ echo abc | ./a.out
ab
$ ./a.out file1
ab
假设 file1 的内容也是 'abc'
目标是让它像标准的 Unix 工具一样工作(但允许不使用任何命令行选项,即“./a.out -w somefile”)。
如何处理命令行参数“-”?
最佳答案
通常,Unix 实用程序将仅由 -
组成的参数解释为等同于 stdin
,如果它可以被解释为输入文件,或等同于 stdout
如果它肯定会被解释为输出文件。
在这种情况下,如果它是一个命名文件,它将是一个输入文件,因此它通常等同于 stdin
。
这是 Posix 准则 #13 Utility Syntax Guidelines :
Guideline 13:
For utilities that use operands to represent files to be opened for either reading or writing, the
-
operand should be used to mean only standard input (or standard output when it is clear from context that an output file is being specified) or a file named-
.
关于为 C 编写标准 unix 程序时的命令行参数 "−",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48981712/