How Do I Pipe a String Into a popen() Command in C? How Do I Pipe a String Into a popen() Command in C? unix unix

How Do I Pipe a String Into a popen() Command in C?


If you need to get a string into the md5 program, then you need to know what options your md5 program works with.

  • If it takes a string explicitly on the command line, then use that:

    md5 -s 'string to be hashed'
  • If it takes standard input if no file name is given on the command line, then use:

    echo 'string to be hashed' | md5
  • If it absolutely insists on a file name and your system supports /dev/stdin or /dev/fd/0, then use:

    echo 'string to be hashed' | md5 /dev/stdin
  • If none of the above apply, then you will have to create a file on disk, run md5 on it, and then remove the file afterwards:

    echo 'string to be hashed' > file.$$; md5 file.$$; rm -f file.$$


See my comment above:

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

produces an md5 sum


Try this:

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}

If you really want to write it to md5's stdin, and then read from md5's stdout, you're probably going to want to look around for an implementation of popen2(...). That's not normally in the C library though.