C++ 以stdin作为文件名参数的fopen
我被要求编写一个程序,基本上解析给定给它的文件,并重定向stdin,如下所示:C++ 以stdin作为文件名参数的fopen,c++,fopen,io-redirection,C++,Fopen,Io Redirection,我被要求编写一个程序,基本上解析给定给它的文件,并重定向stdin,如下所示: myProg参数1参数2参数3
myProg参数1参数2参数3
我试图使用fopen函数来打开给定的文件,但我不明白在“const char*filename”参数中应该给出什么 您不需要打开该文件。您的程序有一个名为
stdin
的特殊值,其中包含进程标准输入流的句柄。您可以像使用文件句柄一样使用它,例如:
int c = fgetc( stdin );
或:
使用freopen
从Unix手册页:
#include < stdio.h >
FILE *freopen(const char *filename, const char *mode, FILE
*stream);
#包括<标准高度>
文件*freopen(常量字符*文件名,常量字符*模式,文件
*溪流);
您根本不应该打开任何东西,因为stdin已被重定向,因此您只需将此stdin句柄用于标准文件功能,即:
while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input
// Do something with data stored in buffer
}
@Molly所以使用fread-你可以使用stdin的所有流读取功能。
while (fread(buf, 1, 1024, stdin) != 0) { // Read the data from input
// Do something with data stored in buffer
}