APUE Learning Example Source Code
guowenxue
2023-11-06 7856bf3569cc448fe3b360c3fca836593a0c0c7d
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
71
72
73
74
75
76
77
78
79
/*********************************************************************************
 *      Copyright:  (C) 2023 LingYun IoT System Studio.
 *                  All rights reserved.
 *
 *       Filename:  mycp.c
 *    Description:  This file file copy example code, don't not support foler.
 *
 *        Version:  1.0.0(2023年08月09日)
 *         Author:  Guo Wenxue <guowenxue@gmail.com>
 *      ChangeLog:  1, Release initial version on "2023年08月09日 10时09分57秒"
 *
 ********************************************************************************/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <errno.h>
#include <unistd.h>
#include <libgen.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
 
int main (int argc, char **argv)
{
    struct stat    sbuf;
    char          *progname = basename(argv[0]);
    char          *src, *dst;
    int            fd_src, fd_dst;
    char           buf[2048];
    int            rv, left;
 
    if( argc != 3 )
    {
        printf("Usage: %s [src] [dst]\n", progname);
        return 0;
    }
    src = argv[1];
    dst = argv[2];
 
    /* check file type */
    if( stat(src, &sbuf) )
    {
        printf("%s: cannot stat '%s': %s\n", progname, src, strerror(errno));
        return 2;
    }
 
    if( !S_ISREG(sbuf.st_mode) )
    {
        printf("%s: %s is not text file\n", progname, src);
        return 3;
    }
 
    /* open files */
    if( (fd_src=open(src, O_RDONLY)) < 0 )
    {
        printf("%s: open '%s' failure: %s\n", progname, src, strerror(errno));
        return 4;
    }
 
    if( (fd_dst=open(dst, O_RDWR|O_TRUNC|O_CREAT, sbuf.st_mode&0x777)) < 0 )
    {
        printf("%s: open '%s' failure: %s\n", progname, dst, strerror(errno));
        return 5;
    }
 
    /* copy file content */
    left = sbuf.st_size;
    while( left > 0 )
    {
        rv = read(fd_src, buf, sizeof(buf));
        if( rv > 0)
        {
            rv = write(fd_dst, buf, rv);
            left -= rv;
        }
    }
 
    return 0;
}