代码之家  ›  专栏  ›  技术社区  ›  Ash

如何在C中将字符串导入popen()命令?

  •  4
  • Ash  · 技术社区  · 14 年前

    我在为uni工作的C语言中(第一次或多或少),我需要从字符数组生成一个MD5。指定必须通过创建管道并执行 md5 系统上的命令。

    我已经走了这么远了:

    FILE *in;
    extern FILE * popen();
    char buff[512];
    
    /* popen creates a pipe so we can read the output
     * of the program we are invoking */
    char command[260] = "md5 ";
    strcat(command, (char*) file->name);
    if (!(in = popen(command, "r"))) {
        printf("ERROR: failed to open pipe\n");
        end(EXIT_FAILURE);
    }
    

    现在这非常有效(对于任务的另一部分,它需要为文件获取MD5),但我无法训练如何在其中输入字符串。

    如果我理解正确,我需要做如下的事情:

    FILE * file = popen("/bin/cat", "w");
    fwrite("hello", 5, file);
    pclose(file);
    

    我想,这会执行cat,并通过stdin将“hello”传递给它。这是对的吗?

    3 回复  |  直到 14 年前
        1
  •  2
  •   Jonathan Leffler    14 年前

    md5

    • md5 -s 'string to be hashed'
      
    • echo 'string to be hashed' | md5
      
    • /dev/stdin /dev/fd/0

      echo 'string to be hashed' | md5 /dev/stdin
      
    • echo 'string to be hashed' > file.$$; md5 file.$$; rm -f file.$$
      
        2
  •  1
  •   prelic    14 年前

    FILE* file = popen("/sbin/md5","w");
    fwrite("test", sizeof(char), 4, file);
    pclose(file);
    

        3
  •  0
  •   xscott    14 年前

    static char command[256];
    snprintf(command, 256, "md5 -qs '%s'", "your string goes here");
    FILE* md5 = popen(md5, "r");
    static char result[256];
    if (fgets(result, 256, md5)) {
         // got it
    }