home *** CD-ROM | disk | FTP | other *** search
/ Microsoft Programmer's Library 1.3 / Microsoft-Programers-Library-v1.3.iso / sampcode / qc / qc25 / copyfile.c < prev    next >
Encoding:
C/C++ Source or Header  |  1989-11-15  |  2.0 KB  |  75 lines

  1. /* COPYFILE.C: Demonstrate malloc and free functions */
  2.  
  3. #include <stdio.h>     /* printf function and NULL */
  4. #include <io.h>        /* low-level I/O functions */
  5. #include <conio.h>     /* getch function */
  6. #include <sys\types.h> /* struct members used in stat.h */
  7. #include <sys\stat.h>  /* S_ constants */
  8. #include <fcntl.h>     /* O_ constants */
  9. #include <malloc.h>    /* malloc function */
  10. #include <errno.h>     /* errno global variable */
  11.  
  12. int copyfile( char *source, char *destin );
  13.  
  14. main( int argc, char *argv[] )
  15. {
  16.    if( argc == 3 )
  17.       if( copyfile( argv[1], argv[2] ) )
  18.          printf( "Copy failed\n" );
  19.       else
  20.          printf( "Copy successful\n" );
  21.    else
  22.       printf( "  SYNTAX: COPYFILE <source> <target>\n" );
  23.  
  24.    return 0;
  25. }
  26.  
  27. int copyfile( char *source, char *target )
  28. {
  29.    char *buf;
  30.    int hsource, htarget, ch;
  31.    unsigned count = 50000;
  32.  
  33.    if( (hsource = open( source, O_BINARY | O_RDONLY )) == - 1 )
  34.       return errno;
  35.    htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_EXCL,
  36.                            S_IREAD | S_IWRITE );
  37.    if( errno == EEXIST )
  38.    {
  39.       cputs( "Target exists. Overwrite? " );
  40.       ch = getch();
  41.       if( (ch == 'y') || (ch == 'Y') )
  42.          htarget = open( target, O_BINARY | O_WRONLY | O_CREAT | O_TRUNC,
  43.                                  S_IREAD | S_IWRITE );
  44.       printf( "\n" );
  45.    }
  46.    if( htarget == -1 )
  47.       return errno;
  48.  
  49.    if( filelength( hsource ) < count )
  50.       count = (int)filelength( hsource );
  51.  
  52.    buf = (char *)malloc( (size_t)count );
  53.  
  54.    if( buf == NULL )
  55.    {
  56.       count = _memmax();
  57.       buf = (char *)malloc( (size_t)count );
  58.       if( buf == NULL )
  59.          return ENOMEM;
  60.    }
  61.  
  62.    while( !eof( hsource ) )
  63.    {
  64.       if( (count = read( hsource, buf, count )) == -1 )
  65.          return errno;
  66.       if( (count = write( htarget, buf, count )) == - 1 )
  67.          return errno;
  68.    }
  69.  
  70.    close( hsource );
  71.    close( htarget );
  72.    free( buf );
  73.    return 0;
  74. }
  75.