tags:

views:

182

answers:

2

I have a C code.. i which I have following code for UNIX:

l_iRet = system( "/bin/cp -p g_acOutputLogName g_acOutPutFilePath");

when I am running the binary generated..I am getting the following error:

cp: cannot access g_acOutputLogName

Can any one help me out?

+1  A: 

Presumably g_acOutputLogName and g_acOutPutFilePath are char[] (or char*) variables in your program, rather than the actual paths involved.

You need to use the values stored therein, rather than the variable names, for example:

char command[512];    
snprintf( command, sizeof command, "/bin/cp -p %s %s", 
          g_acOutputLogName, g_acOutPutFilePath );
l_iRet = system( command );
martin clayton
Thanks a lot..It was really helpful..Thanks again
+1  A: 

You should generally prefer the exec family of functions over the system function. The system function passes the command to the shell which means that you need to worry about command injection and accidental parameter expansion. The way to call a subprocess using exec is as follows:

pid_t child;
child = fork();
if (child == -1) {
  perror("Could not fork");
  exit(EXIT_FAILURE);
} else if (child == 0) {
  execlp("/bin/cp", g_acOutputLogName, g_acOutPutFilePath, NULL);
  perror("Could not exec");
  exit(EXIT_FAILURE);
} else {
  int childstatus;
  if (waitpid(child, &childstatus, 0) == -1) {
    perror("Wait failed");
  }
  if (!(WIFEXITED(childstatus) && WEXITSTATUS(childstatus) == EXIT_SUCCESS)) {
    printf("Copy failed\n");
  } 
}
Geoff Reedy