questions about a backup program for the MS-DOS environment

Walter Bright bright at Data-IO.COM
Thu May 3 07:39:58 AEST 1990


In article <12459 at wpi.wpi.edu> jhallen at wpi.wpi.edu (Joseph H Allen) writes:
<In article <1990Apr25.125806.20450 at druid.uucp> darcy at druid.UUCP (D'Arcy J.M. Cain) writes:
<<In article <255 at uecok.UUCP> dcrow at uecok (David Crow -- ECU Student) writes:
<<<      - possibly a faster copying scheme.  the following is the
<<<         code I am using to copy from one file to another:
<<<            do
<<<            {  n = fread(buf, sizeof(char), MAXBUF, infile);
<<<               fwrite(buf, sizeof(char), n, outfile);
<<<            } while (n == MAXBUF);        /* where MAXBUF = 7500 */
<<Try:
<<     while ((n = fread(buf, sizeof(char), BUFSIZ, infile)) != 0)
<<		fwrite(buf, sizeof(char), n, outfile);
<<
<<By using BUFSIZ instead of your own buffer length you get a buffer size
<<equal to what the fread and fwrite routines use.  
<No, no, no Yuck!  Don't use the C functions, and don't use such tiny buffers.
<(no wonder it's so slow :-) Try (in small or tiny model):
<	[asm example deleted]

There is no point in going to asm to get high speed file copies. Since it
is inherently disk-bound, there is no sense (unless tiny code size is
the goal). Here's a C version that you'll find is as fast as any asm code
for files larger than a few bytes (the trick is to use large disk buffers):


#if Afilecopy
int file_copy(from,to)
#else
int file_append(from,to)
#endif
char *from,*to;
{	int fdfrom,fdto;
	int bufsiz;

	fdfrom = open(from,O_RDONLY,0);
	if (fdfrom < 0)
		return 1;
#if Afileappe
	/* Open R/W by owner, R by everyone else	*/
	fdto = open(to,O_WRONLY,0644);
	if (fdto < 0)
	{   fdto = creat(to,0);
	    if (fdto < 0)
		goto err;
	}
	else
	    if (lseek(fdto,0L,SEEK_END) == -1)	/* to end of file	*/
		goto err2;
#else
	fdto = creat(to,0);
	if (fdto < 0)
	    goto err;
#endif

	/* Use the largest buffer we can get	*/
	for (bufsiz = 0x4000; bufsiz >= 128; bufsiz >>= 1)
	{   register char *buffer;

	    buffer = (char *) malloc(bufsiz);
	    if (buffer)
	    {   while (1)
		{   register int n;

		    n = read(fdfrom,buffer,bufsiz);
		    if (n == -1)		/* if error		*/
			break;
		    if (n == 0)			/* if end of file	*/
		    {   free(buffer);
			close(fdto);
			close(fdfrom);
			return 0;		/* success		*/
		    }
		    n = write(fdto,buffer,(unsigned) n);
		    if (n == -1)
			break;
		}
		free(buffer);
		break;
	    }
	}
err2:	close(fdto);
	remove(to);				/* delete any partial file */
err:	close(fdfrom);
	return 1;
}



More information about the Comp.lang.c mailing list