Tuesday, July 14, 2009

Function for copying a file in c language?

for writing nc i should copy file from a drive and paste it in other


drive or location .what function i should use for copying a file.


and also for cuting a file.


notice:i am programing in c.

Function for copying a file in c language?
On UNIX style systems you can execute commands with the system call, for example





system("cp pathname1 pathname2")





Likewise on Windows but with copy instead of cp.





http://www.die.net/doc/linux/man/man3/sy...








Windows has a CopyFile function which can be called from C.





http://msdn.microsoft.com/library/defaul...
Reply:This is not tested and has no real error checking but should get you started.





int copy (char * src, char * dest)


{


char buf[1024];


FILE * in, *out;





in = fopen(src, "r");


if(in == NULL)


{


return(-1);


}





out = fopen(dest,"w");


if(out == NULL)


{


return(-1);


}





while(fread( buf,


sizeof(buf),


1,


in))


{


fwrite(buf,


sizeof(buf),


1,


out);


}


fclose(in);


fclose(out);


return(0);


}
Reply:Or you can have the program do it with the appropriate calls. Use C file I/O to open the file, write it to another file at the new location, close both. Then make calls to appropriate functions to delete the old files if needed. I beleive that unlink works in *nix and kill works under DOS or DOS box. You'll have to look up the Windows functions if you need it in the Win32 or Win32s APIs. I hope this helps.
Reply:DanD is quite rignt. One additional detail: you can use function "system" in DOS and Windows also.


system( "copy pathname_1 pathname_2" );


If you want to "cut" the file call then


system( "del pathname_1" ) for Windows


of


system( "rm pathname_1" ) for *NIX


No comments:

Post a Comment