Search code examples
cfilemd5sum

Redirect md5sum to a file using execvp?


i need to get the checksum of a file using md5sum, inside a C project.

I can't use the openssl library because it isn´t installed, and i can't install it, because it's the university server that i'm working on.

Also i have some requirements, and i can not use system(), which would be very simple to just: system("md5sum fileName > testFile");

They also don't allow me to use popen();

Im trying to make it work using execvp, but it's not actually working, and i don't know if i can actually work.

The test file that im actually using is this:

  int main(){

      char *const args[] = {"md5sum","file"," > ","test", NULL};                                                                                                                                             

      execvp(args[0],args);  

      return 0;
  }

When i open the file "test" nothing is writed there,

Any clue on how to do it, or why it isn't working??

Thanks in advance.


Solution

  • You are passing > as an argument to the command. Usually writing command > file works because the shell that you are using parses > as redirection symbol and redirects the standard output of your program to the file ( > is never passed to the command itself).

    What you are trying to is

    int main()
    {
        const char* args[]={"md5sum","file",0};
        int fd=open("test",O_CREAT|O_WRONLY,S_IRWXU);
        pid_t pid=fork();
    
        if(!pid)
        {
             dup2(fd,STDOUT_FILENO);
             close(fd);
             execvp(agrs[0],args);
        }
     // ...
    
     }