6

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

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

4

3 回答 3

12

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

int c = fgetc( stdin );

或者:

fread( somebuffer, somesize, 1, stdin );
于 2011-04-26T11:26:38.727 回答
1

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

while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input
  // Do something with data stored in buffer
}
于 2011-04-26T11:28:56.150 回答
0

使用自由打开。

从 Unix 手册页:

#include <stdio.h>

     FILE *freopen(const char *filename, const char *mode, FILE
     *溪流);

于 2011-04-26T11:27:44.840 回答