阅读从管道命令文件名(Reading a file name from piped command)

2019-07-23 13:14发布

所以我试图让C程序来读取按以下格式在命令行中的文件名:猫(文件名路径)| (项目名称)

我可以得到它读取输入文件名时,它作为命令行参数输入,但它不会从相连的说法阅读

这里的代码,现在它的读取文件的名称,就好像在命令行程序名后写的。

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

任何帮助,将不胜感激

Answer 1:

你的程序无法获取文件名的原因是因为你没有把它给它。

如果你运行你的程序为:

prog hello.txt

它给出的说法hello.txtargc/argv

但是,你正在做的是:

cat hello.txt | prog

这意味着外壳打开文件,并将其进给到你的程序的标准输入。 实际上,为了更准确, cat被打开文件和壳被简单的标准输出连接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就是一个例子-它显示的文件名(S)如果知道他们:

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


Answer 2:

管道内容到过程并没有把值代入argv ; 相反,它把值设置到该进程的stdin

您需要检查是否argc大于1,如果是,则argv[1]有你已经给出的文件名(当然,第一个参数的程序,反正)。 如果不是,则需要从读stdin来获取文件名。



Answer 3:

为了从contantenated阅读,你需要从标准输入读取

char c = (char)fgetc(stdin)


文章来源: Reading a file name from piped command
标签: c pipe filenames