我被要求编写一个程序,基本上解析给它的文件,重定向stdin,如下所示:
myProg param1 param2 param3< theFileToParse
我正在尝试使用fopen函数来打开给定的文件,但我不明白我应该在'const char * filename'参数中给出它。
答案 0 :(得分:10)
您无需打开该文件。您的程序有一个名为stdin
的特殊值,它包含进程标准输入流的句柄。您可以像使用文件句柄一样使用它,例如:
int c = fgetc( stdin );
或:
fread( somebuffer, somesize, 1, stdin );
答案 1 :(得分:1)
你根本不应该打开任何东西,因为stdin 已经重定向,所以你可以简单地将这个stdin句柄用于标准文件函数,即:
while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input
// Do something with data stored in buffer
}
答案 2 :(得分:0)
使用freopen。
从Unix手册页:
#include < stdio.h > FILE *freopen(const char *filename, const char *mode, FILE *stream);