Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I copy files in C without platform dependency?

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 )

like image 512
lqez Avatar asked Jul 24 '11 15:07

lqez


People also ask

What is copy to Output directory?

"Copy to Output Directory" is the property of the files within a Visual Studio project, which defines if the file will be copied to the project's built path as it is. Coping the file as it is allows us to use relative path to files within the project.

How do I duplicate files using the command line?

Highlight the files you want to copy. Press the keyboard shortcut Command + C . Move to the location you want to move the files and press Command + V to copy the files.

How do I copy files in Linux?

The Linux cp command is used for copying files and directories to another location. To copy a file, specify “cp” followed by the name of a file to copy. Then, state the location at which the new file should appear. The new file does not need to have the same name as the one you are copying.


1 Answers

The system() function is a lot more trouble than it's worth; it invokes the shell in a seperate proccess, and should usually be avoided.

Instead fopen() a.txt and dest/b.text, and use getc()/putc() to do the copying (because the standard library is more likely to do page-aligned buffering than you)

FILE *src = fopen("a.txt", "rb");
FILE *dst = fopen("dest/b.txt", "wb");
int i;
for (i = getc(src); i != EOF; i = getc(src))
{
    putc(i, dst);
}
fclose(dst);
fclose(src);
like image 178
Dave Avatar answered Sep 19 '22 05:09

Dave