Quick-and-Dirty Method to Copy Files in C++ - dummies

Quick-and-Dirty Method to Copy Files in C++

By John Paul Mueller, Jeff Cogswell

There’s a quick-and-dirty way you can copy a file, and you can use this to also move, delete, and rename files. However, this method is absolutely not portable: in effect, if you do this on Windows, for example, you won’t be able to run the same application on Unix, and vice versa. That is, you have to make a version for the operating system you’re using.

Now, if you’re familiar with DOS (remember that?) or the Unix shell, you can execute any DOS or Unix-shell commands by using the system function. If you use Dev-C++, you’ve already seen the system function many times:

system("PAUSE");

This runs the DOS pause command, which prints the message

Press any key to continue …

and waits for you to press the Any key (or any other key for that matter). Because the system function can run any DOS or shell command, you can use it to call the DOS copy command, like this:

system("copy c:\abc.txt c:\def.txt");

Note that you have to use the backslash, not a forward slash; DOS really doesn’t like forward slashes. To make the command DOS-friendly, use two backslashes inside the string.

When you use this approach, you can run into some strange situations. For example, if you write an application that calls system and you’re planning to run it under the Cygwin environment in Windows, you can use the Unix-style cp command instead of the DOS copy command. The resulting weird command looks like this:

system("cp c:\abc.txt c:\def.txt");

But you can only use this command under the Cygwin environment. Otherwise it gives you a huffy error message:

'cp' is not recognized as an internal or external command, operable ­program or batch file.

Moral: You have to make sure that whatever command you call in the system function really exists in the environment from which you issue the call.