It looks like this question is pretty simple but I can’t find the clear solution for copying files in C without platform dependency.
I used a system() call in my open source project for creating a directory, copying files and run external programs. It works very well in Mac OS X and other Unix-ish systems, but it fails on Windows. The problem was:
system( "cp a.txt destination/b.txt" );
- Windows uses backslashes for path separator. (vs slashes in Unix-ish)
- Windows uses ‘copy’ for the internal copy command. (vs cp in Unix-ish)
How can I write a copying code without dependency?
( Actually, I wrote macros to solve this problems, but it’s not cool. http://code.google.com/p/npk/source/browse/trunk/npk/cli/tests/testutil.h, L22-56 )
You need to use the C standard library functions in stdio.h.
In particular,
fopen,fread,fwrite, andfclosewill be sufficient.Be sure to include the
b(“binary”) option in the flags tofopen.[edit]
Unfortunately, the file names themselves (forward-slashes vs. back-slashes) are still platform dependent. So you will need some sort of
#ifdefor similar to deal with that.Or you can use a cross-platform toolkit.