通过管道文件在C exclusivley中使用stdin

问题描述 投票:0回答:2

我为一个项目编写了一个文件解析器,用于解析命令行中提供的文件。

但是,我也想允许用户输入输入[,但是仅通过命令行重定向。

((使用基于Linux的命令提示符)以下命令

应该产生相同的结果

    ./ check infile.txt(通过命令行输入文件名)
  1. ./ check
  2. cat infile.txt | ./check
  • EDIT FOR CLARITY

  • :可执行文件应接受文件名作为第一个也是唯一的命令行参数。如果未指定文件名,则应从标准输入中读取。

    EDIT 2

    :我意识到这真的很简单,并发布了答案。我将在某些时候将其留给其他可能需要它的人使用
    c file parsing stdin
    2个回答
    0
    投票
    我想我的大脑很虚弱,因为这是一个非常基本的问题,我在发布它后就将其与之相关。我将其留给可能需要它的其他人使用。

    答案:

    您可以从stdin中获取,然后要检查文件的末尾,您仍然可以通过使用以下命令将feof用于stdin:while(!feof(stdin))


    0
    投票
    这很危险地接近“请为我编写程序”。也许它甚至越过了那条线。仍然,这是一个非常简单的程序。

    我们假设您有一个解析器,它使用单个FILE*参数并解析该文件。 (如果您编写了一个使用const char*文件名的解析函数,那么这是通过解释为什么这样做是一个坏主意。函数应该只做一件事,而“打开文件然后解析它”则是两件事。一旦编写了一个函数,该函数执行两项无关的操作,就会立即遇到您只想执行其中一项的情况(例如仅解析流而不打开文件。)

    因此使我们拥有:

    #include <errno.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include "myparser.h" /* Assume that myparser.h includes * int parseFile(FILE* input); * which returns non-zero on failure. */ int main(int argc, char* argv[]) { FILE* input = stdin; /* If nothing changes, this is what we parse */ if (argc > 1) { if (argc > 2) { /* Too many arguments */ fprintf(stderr, "Usage: %s [FILE]\n", argv[0]); exit(1); } /* The convention is that using `-` as a filename is the same as * specifying stdin. Just in case it matters, follow the convention. */ if (strcmp(argv[1], "-") != 0) { /* It's not -. Try to open the named file. */ input = fopen(argv[1], "r"); if (input == NULL) { fprintf(stderr, "Could not open '%s': %s\n", argv[1], strerror(errno)); exit(1); } } } return parse(input); }

    将以上大部分内容打包到一个接受文件名并返回打开的FILE*的函数中可能会更好。
    © www.soinside.com 2019 - 2024. All rights reserved.