summaryrefslogtreecommitdiff
path: root/reference/C/CONTRIB/OR_PRACTICAL_C/13_2.c
blob: a1dd50c245f32e3846363b581c844cd49bbb22ef (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
/****************************************
 * copy -- copy one file to another.    *
 *                                      *
 * Usage                                *
 *      copy <from> <to>                *
 *                                      *
 * <from> -- the file to copy from      *
 * <to>   -- the file to copy into      *
 ****************************************/
#include <stdio.h>
#ifndef __MSDOS__       /* if we are not MS-DOS */
#define __UNIX__        /* then we are UNIX */
#endif __MSDOS__

#include <stdlib.h>     /* ANSI Standard C file */

#ifdef __UNIX__
#include <sys/types.h>  /* file defines for UNIX filesystem */
#include <sys/stat.h>
#include <fcntl.h>
#endif __UNIX__

#ifdef __MSDOS__
#include <fcntl.h>     /* file defines for DOS filesystem */
#include <sys\stat.h>
#include <io.h>
#endif __MSDOS__

void  exit();                   /* lib routine */

#define BUFFER_SIZE (16 * 1024) /* use 16K buffers */

main(int argc, char *argv[])
{
    char  buffer[BUFFER_SIZE];  /* buffer for data */
    int   in_file;              /* input file descriptor */
    int   out_file;             /* output file descriptor */
    int   read_size;            /* number of bytes on last read */

    if (argc != 3) {
        (void) fprintf(stderr, "Error:Wrong number of arguments\n");
        (void) fprintf(stderr, "Usage is: copy <from> <to>\n");
        exit(8);
    }
    in_file = open(argv[1], O_RDONLY);
    if (in_file < 0) {
        (void) fprintf("Error:Unable to open %s\n", argv[1]);
        exit(8);
    }
    out_file = open(argv[2], O_WRONLY | O_TRUNC | O_CREAT, 0666);
    if (out_file < 0) {
        (void) fprintf("Error:Unable to open %s\n", argv[2]);
        exit(8);
    }
    while (1) {
        read_size = read(in_file, buffer, sizeof(buffer));

        if (read_size == 0)
            break;              /* end of file */

        if (read_size < 0) {
            (void) fprintf(stderr, "Error:Read error\n");
            exit(8);
        }
        (void) write(out_file, buffer, (unsigned int) read_size);
    }
    (void) close(in_file);
    (void) close(out_file);
    return (0);
}