John P Raj
John P Raj

Reputation: 33

MD5 hash of a string which is already md5 hashed: Syntax error

I wanted to generate md5 hash of a string which is already md5 hashed. This is what I have done! I have looped it but unfortunately, it is showing some error "sh: 2: Syntax error: "|" unexpected". I hope it has something to do with "strcat" inside the loop. Somehow inside the loop the lines

strcpy(command,"echo ");
strcat(command,str);

are ignored. I am lost here!

Can anybody help me out?

#include <stdio.h>
#include <string.h>
#include <sys/types.h>
#include <stdlib.h>
#include <stdlib.h>
#include <unistd.h>

int main()
{
   FILE *fp;
   char str[100], command[100];
   char var[100];
   int i;
   printf("Enter the string:\n");
   scanf("%[^\n]s",str);
   printf("\nString is: %s\n\n",str);
   for (i=0; i<3; i++) {
       strcpy(command,"echo ");
       strcat(command,str);
       strcat(command," | md5sum");
       strcat(command," | cut -c1-32");
       fp = popen(command, "r");
       fgets(var, sizeof(var), fp);
       pclose(fp);
       strcpy(str,var);
   }
   printf("The md5 has is :\n");
   printf("%s\n", var);   
   return 0;     

}

Upvotes: 0

Views: 139

Answers (1)

Mathieu
Mathieu

Reputation: 9659

Your problem comes from the fgets which keep linefeed on read buffer.

From man fgets:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte (\0) is stored after the last character in the buffer.

So you may want to replace the \n by some \0. You can do it with strcspn:

   ...           
   fgets(var, sizeof(var), fp);
   pclose(fp);
   strcpy(str,var);

   /* remove first \n in str*/
   str[strcspn(str, "\n")] = '\0';

   ...

Upvotes: 1

Related Questions