mike.h on Sat, 15 Jun 2002 20:10:14 +0200


[Date Prev] [Date Next] [Thread Prev] [Thread Next] [Date Index] [Thread Index]

Re: [PLUG] unix cp function call (thanks)


On Friday 14 June 2002 08:33 pm, you wrote:
> On Fri, Jun 14, 2002 at 04:31:00PM -0400, Bill Jonas wrote:
> > On Fri, Jun 14, 2002 at 04:26:56PM -0400, Walt Mankowski wrote:
> > > Or you can call system(3).
> >
> > Oh, right, there's that too, which is nicer and takes care of all that
> > for you.  Can you tell I don't really do C all that much? ;-)
>
> Security issues aside, don't forget that files can have holes. If you
> want to be sophisticated about copying, you have to look at inodes and
> stuff.
>
>     /* Won't compile without correcting syntax */
>     FILE *fp = fopen("/tmp/foo", "w");
>     fputc('a', fp);
>     fseek(fp, 10000000, SEEK_CUR);
>     fputc('b', fp);
>     fclose(fp);
>
> I wrote two bytes, used two blocks (not counting inode, directory,
> your copy could make a 10 MB file.

Is there any reason (besides perhaps portabilty to M$) not to use read(2) and 
write(2) ?? This will copy non-text files too.  For example (leaving out 
error chks for simplicity). 
	...
	include <unistd.h>
	#define MAXBUFS 1024
	...
	int buf[MAXBUFS];
	size_t bytes_read;
	int source, dest;
	char *src, *dst;

	src ="/path/to/source/to/copy";    /* file can be *.png, *.jpg, etc.. */
	dst ="/path/to/duplicate/file.png";

	source = open(src, O_RDONLY, 0);
	dest = creat(dst, 0700);   /* stat first to prevent overwriting existing */

	while((bytes_read= read(source, buf, MAXBUFS)) > 0)
		write(dest, buf, bytes_read);

	close(dest);
	close(source);

-- 
mike.h@acm.org
mike.h@stemik.com


______________________________________________________________________
Philadelphia Linux Users Group       -      http://www.phillylinux.org
Announcements-http://lists.phillylinux.org/mail/listinfo/plug-announce
General Discussion  -  http://lists.phillylinux.org/mail/listinfo/plug