Search code examples
cexecl

How to copy files to folder with execlp?


I need to copy a file (the name of the file is entered via the keyboard) inside a folder (called backup) using execpl

printf("File name to copy? ");
scanf(" %99[^\n]", str);

char *args[] = { "cp", str,"/backup" };

p = fork();  
// Fork validations + Dad wait for child

execlp(args[0],args[0], args[1], args[2], NULL);
exit(1);

Solution

  • The first argument to execlp is the command to run, and the arguments that follow are the command line arguments to the command. The first of these arguments is always the program being run.

    So you need to duplicate the first element in the array:

    execlp(args[0], args[0], args[1], args[2], NULL);