c - 如何读取 C 中的管道内容?

标签 c stdin pipe

我希望能够做到这一点:

$ echo "hello world" | ./my-c-program
piped input: >>hello world<<

我知道isatty should be used检测 stdin 是否为 tty。如果它不是 tty,我想读出管道内容——在上面的示例中,这是字符串 hello world

在 C 中推荐的方法是什么?

这是我到目前为止得到的:

#include <stdio.h>
#include <unistd.h>

int main(int argc, char* argv[]) {

  if (!isatty(fileno(stdin))) {
    int i = 0;
    char pipe[65536];
    while(-1 != (pipe[i++] = getchar()));
    fprintf(stdout, "piped content: >>%s<<\n", pipe);
  }

}

我编译这个使用:

gcc -o my-c-program my-c-program.c

几乎 工作,除了它似乎总是在管道内容字符串的末尾添加一个 U+FFFD 替换字符和一个换行符(我确实理解换行符)。为什么会发生这种情况,如何避免这个问题?

echo "hello world" | ./my-c-program
piped content: >>hello world
�<<

免责声明:我对 C 没有任何经验。请放轻松。

最佳答案

出现替换符号是因为您忘记了以 NUL 终止字符串。

换行符在那里是因为默认情况下,echo 在其输出的末尾插入 '\n'

如果你不想插入 '\n' 使用这个:

echo -n "test" | ./my-c-program

并删除错误的字符插入

pipe[i-1] = '\0';

在打印文本之前。

请注意,您需要使用 i-1 作为空字符,因为您实现循环测试的方式。在您的代码中,i 在最后一个字符后再次递增。

关于c - 如何读取 C 中的管道内容?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16305971/

相关文章:

python - 在 Windows 上列出串行 (COM) 端口?

c++ - OpenCL get_global_id

io - 使用 Scanf + input + enter 从 stdin 获得双重输入,如何刷新?

perl - 阅读文本的好方法是什么?

linux - Bash 匿名管道

c - 为什么退出函数后指针会恢复?

c - 为什么 getpwuid 在我的系统上调用 connect?

c stdin 二维数组文件输入

linux - Bash shell 脚本,如何在命令中使用管道

C DLL 和新数据服务进程之间基于云的 IPC