Search code examples
cstringsystemtar

Using system() in C with an agument


I wish to write a program that uses system() and compress a folder. The folder name is given via command-line. This is what I have:

#include <stdlib.h>
#include <stdio.h>

int main(int argc, char** argv){
  int i;
  char buf[64]
  char string[]="tar -cf stent.tar ";
  if(argc>1){
    for(i=1;i<argc;i++){
      string[16]=(char)argv[i];
      printf("%s",argv[i]);
    }
  }
  snprintf(buf,sizeof(buf), "tar -cf stent.tar %s," argv);
  printf(string);
  printf(buf);
  return 0;
}

Basically I wish to do this:

system("tar -cf stent.tar %s", buf);

buf should be the input argument of the user. The folders he wants to compress


Solution

  • Perhaps this will pass the folder name argument to the tar command. But it's a mystery why you don't just do it from the command line.

    #include <stdlib.h>
    #include <stdio.h>
    
    int main(int argc, char *argv[]){
        char buf[1024];
        if(argc > 1){
            sprintf(buf, "tar -cf stent.tar %s", argv[1]);
            system(buf);
        }
        return 0;
    }
    

    Leaving the possibility of buffer overflow out of it.