【问题标题】:fopen with the stdin as the filename parameterfopen 使用标准输入作为文件名参数
【发布时间】:2011-04-26 11:24:55
【问题描述】:

我被要求编写一个程序,该程序基本上解析给它的文件,并重定向标准输入,如下所示:
myProg param1 param2 param3

我正在尝试使用 fopen 函数来打开给定的文件,但我不明白我应该在 'const char * filename' 参数中给出什么。

【问题讨论】:

    标签: c++ fopen io-redirection


    【解决方案1】:

    您无需打开文件。您的程序有一个名为stdin 的特殊值,其中包含进程标准输入流的句柄。您可以像使用文件句柄一样使用它,例如:

    int c = fgetc( stdin );
    

    或:

    fread( somebuffer, somesize, 1, stdin );
    

    【讨论】:

    • @Molly 所以使用 fread - 你可以使用标准输入的所有流读取功能。
    【解决方案2】:

    您根本不应该打开任何东西,因为标准输入已已经重定向,因此您可以简单地将此标准输入句柄与标准文件函数一起使用,即:

    while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input
      // Do something with data stored in buffer
    }
    

    【讨论】:

      【解决方案3】:

      使用 freopen。

      从 Unix 手册页:

      #include &lt stdio.h &gt FILE *freopen(const char *filename, const char *mode, FILE *溪流);

      【讨论】:

        猜你喜欢
        • 2013-02-16
        • 1970-01-01
        • 1970-01-01
        • 2018-04-06
        • 2013-11-12
        • 2013-07-10
        • 1970-01-01
        • 2016-04-09
        • 1970-01-01
        相关资源
        最近更新 更多