从管道命令中读取文件名
所以我试图让C程序从命令行读取文件名,格式如下:cat(filename path)| (程序名称)
当输入文件作为命令行参数输入时,我可以让它读取输入文件的名称,但它不会从连接的参数中读取
这是代码,现在它读取文件的名称,就像在命令行上写入程序名称一样。
#include #include //initialize file pointer FILE *file; //initialize global variables #define DEFAULT_LEN 70 //main int main(int argv, char *argc[]){ //open File for reading file = fopen (argc[1],"r"); //test for failure of file open, if failed, print message, quit if(file == NULL){ printf("I'm sorry Dave, I'm araid I can't do that.\n"); printf("Open the file \"%s\" that is.\n", argc[1]); return(0); } //read the first line of a file into an array char temp[DEFAULT_LEN]; //where the read data is put fgets(temp,DEFAULT_LEN,file); //stops at DEFAULT_LEN on \n //print out temp printf("%s\n", temp); //close file, return 0 for main fclose(file); return(0); }
任何帮助,将不胜感激
程序无法获取文件名的原因是因为您没有将其提供给它。
如果您将程序运行为:
prog hello.txt
它在argc/argv
给出了参数hello.txt
。
但是,你正在做的是:
cat hello.txt | prog
这意味着shell正在打开文件并将其提供给程序的标准输入。 实际上,为了更准确, cat
正在打开文件,而shell只是将cat
的标准输出连接到prog
的标准输入。
解决这个问题的一种方法是检查参数的数量( argc
通常是count, argv[]
值,尽管你的代码中有它的迂回方式),如果它是零, argc == 1
,从中读取你的文件标准输入。
只有在给出参数时才打开该文件并阅读它。 这就是许多UNIX实用程序的工作方式:
od -xcb hello.txt # will dump the file. cat hello.txt | od -xcb # will dump the file, but using standard input. echo hello | od -xcb # will dump your "hello" string.
有些甚至根据它们的调用方式改变它们的行为, wc
就是一个例子 – 它显示文件名是否知道它们:
pax> wc -l qq.c 29 qq.c pax> cat qq.c | wc -l 29 pax> wc -l *.c 0 a bc 168 binmath.c 49 qq-save.c 29 qq.c 11 qq2.c 5 qqq.c 18 xx.c 280 total pax> cat *.c | wc -l 280
注意最后一种情况 – 因为所有文件都是通过单个标准输入流呈现的,所以无法分辨出有多少文件。 wc
将统计该流的全部内容。
试试这个:
#include #include #define DEFAULT_LEN 70 int main (int argc, char *argv[]) { FILE *file; // Either select standard input or open the given file. if (argc == 1) { file = stdin; } else { file = fopen (argv[1], "r"); if (file == NULL) { printf ("I'm sorry Dave, I can't do that\n"); printf (" (open the file '%s', that is).\n", argv[1]); return 1; } } // Now you're connected to stdin or the file itself, no // difference in handling them (unless you do weird fseek // sort of stuff). char temp[DEFAULT_LEN]; fgets (temp, DEFAULT_LEN, file); printf ("%s\n", temp); // Only close file if you opened it yourself. if (argc != 1) fclose (file); return 0; }
这允许您使用文件和标准输入方法,如下所示:
pax> prog prog.c #include pax> echo hello | prog hello
将内容管道化为进程并不会将值放入argv
; 相反,它将值放在该进程的stdin
。
您需要检查argc
是否大于1.如果是,则argv[1]
具有您已经给出的文件名(好吧,无论如何,该程序的第一个参数)。 如果没有,您需要从stdin
读取以获取文件名。
要阅读contantenated,您需要阅读STDIN
char c = (char)fgetc(stdin)