C on windows, code for copying files doesn't work

I have this piece of code; it works when you directly write arguments to system()

and doesn't work if you pass arguments to it. Any help please?

char dest[100];
char file[50];
char dir[100];

printf("Enter source path: ");
scanf("%s", dir);

printf("Enter filename: ");
scanf("%s", file);

printf("Enter destination path: ");
scanf("%s", dest);

system("move \"c:\\users\\putty.exe\" g:\\ \n" );  /* <--works        */
system("move \"%s%s\" %s", dir,file,dest);         /* <--doesn't work */

      

+3


source to share


2 answers


You can try this



char dest[100];
char file[50];
char dir[100];
char command[300];
printf("Enter source path: ");
scanf("%s", dir);
printf("Enter filename: ");
scanf("%s", file);
printf("Enter destination path: ");
scanf("%s", dest);
sprintf(command,"move %s%s %s", dir,file,dest);  
system(command); 

      

+5


source


The command is system()

not a replacement snprintf()

. You will need to use snprintf()

and then system()

:

char command[1024];
...
snprintf(command, sizeof(command), "move \"%s%s\" %s", dir, file, dest);
system(command);

      

Or, given that you are on Windows, you can use snprintf_s()

instead snprintf()

. You may also notice that if the user does not leave a backslash at the end of the value dir

, then the last component of the directory and the filename are concatenated. You should probably use:

snprintf(command, sizeof(command), "move \"%s\\%s\" %s", dir, file, dest);

      



While the Windows kernel is quite happy with the forward slash in the path name, the command processor is smaller. Since you are not calling the operating system directly, but rather the shell to run the program, you need to use a backslash, I suppose.

Note that your compiler should have told you what you were calling wrong system()

. The header <stdlib.h>

and indicates that the function only takes one argument.

ISO / IEC 9899: 2011 Β§7.22.4.8 Function system

Summary

ΒΆ1 #include <stdlib.h>

int system(const char *string);

Description

ΒΆ2 If string is a null pointer, the function system

determines whether the host environment has a command processor. If the string is not a null pointer, the system

function passes the string it points to string

, to this command processor it executes in the way that the document should execute; this can cause the program to be called system

to behave inappropriately or to terminate.

If your compiler didn't tell you that you misused the system()

second call or complained about what system()

was declared before using it, then you need to include a warning level in your compilation, or get a better compiler. If that warned you, you need to pay attention to what he says. Remember, the compiler knows more about C than you do.

+3


source