为 C 编写标准 unix 程序时的命令行参数 "−"

标签 c unix

删除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/

相关文章:

c - 为什么没有发生从 unsigned Short int 到signed char 的隐式类型转换?

c++ - 将 .a 文件转换为 .dll

c - 如何让阻塞在 recv() 上的线程优雅地退出?

xml - 如何在不同路径的多个文件上使用 xmlstarlet?

c - 响应 isatty(3) 的文件

c# - 如何通过 C/C++/C# 项目解析并将所有包/类/方法写入数据库?

c - 按位循环左移函数

macos - 当 -i 参数不受支持时,如何使用 grep 和 sed 替换多个文件中的字符串?

c - 为数组动态分配内存时(在 C 中),(int *) 强制转换的作用是什么?

c - 使用格式说明符进行转换