从管道命令中读取文件名

时间:2009-10-14 01:54:33

标签: c pipe filenames

所以我试图让C程序从命令行读取文件名,格式如下: cat(文件名路径)| (节目名称)

当输入文件作为命令行参数输入时,我可以读取输入文件的名称,但它不会从连接的参数中读取

这是代码,现在它正在读取文件的名称,就像在命令行上写入程序名后一样。

#include <stdio.h>
#include <string.h>

//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);
}

任何帮助将不胜感激

3 个答案:

答案 0 :(得分:3)

您的程序无法获取文件名的原因是因为您没有将其提供给它。

如果您将程序运行为:

prog hello.txt

hello.txt中给出了argc/argv参数。

但是,你正在做的是:

cat hello.txt | prog

这意味着 shell 正在打开文件并将其提供给程序的标准输入。实际上,为了更准确,cat正在打开文件,shell只是将cat的标准输出连接到prog的标准输入。

解决这个问题的一种方法是检查参数的数量(argc通常是计数,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 b.c
    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 <stdio.h>
#include <string.h>

#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 <stdio.h>

pax> echo hello | prog
hello

答案 1 :(得分:1)

将内容管道化为流程将值放入argv;相反,它将值放在该进程的stdin

您需要检查argc是否大于1.如果是,则argv[1]具有您已经给出的文件名(好吧,无论如何,该程序的第一个参数)。如果没有,您需要从stdin读取以获取文件名。

答案 2 :(得分:0)

要从contantenated读取,您需要阅读STDIN

char c = (char)fgetc(stdin)
相关问题