tags:

views:

83

answers:

5

There are at least two methods for copying a file in C/C++: procedurally and using ShellExecute. I can post an explanation of each if needed but I'm going to assume that these methods are known. Is there an advantage to using one method over the other?

+3  A: 

Manual methods give you complete control over how you detect and respond to errors. You can program different responses to access control, out of space, hostile file from aliens, whatever. If you call ShellExec (or the moral equivalent on some other platform) you are left with error messages on stderr. Not so hot for an application with a Window-ed UI.

bmargulies
+3  A: 

Procedurally will give you better error checking/reporting and will work cross-platform -- ShellExecute is Windows API only.

You could also use a third-party filesystem library to make the task less annoying -- boost::filesystem is a good choice.

Cory Petosky
+1  A: 

why not use in built programs like system()/ShellExecute:

  1. Your program will not be platform independent
  2. Each call to such function creates a separate executing unit

Pros:

  1. The code is well tested, so more reliable

In such cases, a well tested library is what which is more desirable.

Neeraj
+1  A: 

Call to external applications should be avoided, since often (especially under Windows) they do not return easily understandable error codes and report errors in an undesirable way (stdout, error windows, ...). Moreover, you do not have the full control over the copy, and starting a new application just to do a file copy is often overkill, especially on platforms like Windows, where processes are quite heavyweight objects.

A good compromise could be to use the API that your OS provides you (e.g. CopyFile on Windows), which delivers you surely working code and well-defined error codes.

However, if you want to be cross-platform often the simplest thing to do is just to write your own copy code: after all it's not rocket science, it's a simple task that can be accomplished in a few rows of standard C++ code.

Matteo Italia
+1  A: 

In case with shell you are gaining the convenience of having best available implementation(s) of functionality implemented by OS vendor at cost of added complexity of cross process integration. Think about handling errors, asynchronous nature of file operations, accidental losses of return error level, limited or non-existent control over progress of completion, inability to respond to "abort"/"retry"/"continue" interactive requests etc.

RocketSurgeon