Ash
Ash

Reputation: 25652

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

Im working in c (more or less for the first time) for uni, and I need to generate an MD5 from a character array. The assignment specifies that this must be done by creating a pipe and executing the md5 command on the system.

I've gotten this far:

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

Now this works perfectly (for another part of the assignment which needs to get the MD5 for a file) but I cant workout how to pipe a string into it.

If I understand correctly, I need to do something like:

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

Which, I think, would execute cat, and pass "hello" into it through StdIn. Is this right?

Upvotes: 5

Views: 2823

Answers (3)

Jonathan Leffler
Jonathan Leffler

Reputation: 753675

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.$$
    

Upvotes: 2

prelic
prelic

Reputation: 4518

See my comment above:

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

produces an md5 sum

Upvotes: 1

xscott
xscott

Reputation: 2420

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.

Upvotes: 0

Related Questions