Important Notice
The pages on this site contain documentation for very old MS-DOS software,
purely for historical purposes.
If you're looking for up-to-date documentation, particularly for programming,
you should not rely on the information found here, as it will be woefully
out of date.
COPY1.C
◄Up► ◄Contents► ◄Index► ◄Back►
────────────────────────────────────────────────────────────────────────────
/* COPY1.C illustrates low-level file I/O and dynamic memory allocation
* functions including:
* open close
* read write eof
* malloc free _memmax
*
* Also the global variable:
* errno
*
* See COPY2.C for another version of the copyfile function and
* HEAPBASE.C for an example of based heap management.
*/
#include <io.h>
#include <conio.h>
#include <stdio.h>
#include <fcntl.h> /* O_ constant definitions */
#include <sys\types.h>
#include <sys\stat.h> /* S_ constant definitions */
#include <malloc.h>
#include <errno.h>
int copyfile( char *source, char *destin ); /* Prototype */
void main( int argc, char *argv[] )
{
if( argc == 3 )
if( copyfile( argv[1], argv[2] ) )
printf( "Copy failed\n" );
else
printf( "Copy successful\n" );
else
printf( " SYNTAX: COPY1 <source> <target>\n" );
}
/* Copies one file to another (both specified by path). Dynamically
* allocates memory for the file buffer. Prompts before overwriting
* existing file. Returns 0 if successful, otherwise an error number.
*/
int copyfile( char *source, char *target )
{
char *buf;
int hsource, htarget, ch;
unsigned count = 0xff00;
/* Open source file and create target, overwriting if necessary. */
if( (hsource = open( source, O_BINARY | O_RDONLY )) == - 1 )
return errno;
htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_EXCL,
S_IREAD | S_IWRITE );
if( errno == EEXIST )
{
cputs( "Target exists. Overwrite? " );
ch = getch();
if( (ch == 'y') || (ch == 'Y') )
htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC,
S_IREAD | S_IWRITE );
printf( "\n" );
}
if( htarget == -1 )
return errno;
if( filelength( hsource ) < count )
count = (int)filelength( hsource );
/* Dynamically allocate a large file buffer. If there's not enough
* memory for it, find the largest amount available on the near heap
* and allocate that. This can't fail, no matter what the memory model.
*/
if( (buf = (char *)malloc( (size_t)count )) == NULL )
{
count = _memmax();
if( (buf = (char *)malloc( (size_t)count )) == NULL )
return ENOMEM;
}
/* Read-write until there's nothing left. */
while( !eof( hsource ) )
{
/* Read and write input. */
if( (count = read( hsource, buf, count )) == -1 )
return errno;
if( (count = write( htarget, buf, count )) == - 1 )
return errno;
}
/* Close files and release memory. */
close( hsource );
close( htarget );
free( buf );
return 0;
}