linux下的cp.c编写

来源:互联网 发布:最新版淘宝下载安装 编辑:程序博客网 时间:2024/04/28 23:22

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>

#define BUFFERSIZE 4096
#define COPYMODE   0644

void oop(char *, char *);

int main(int argc, char *argv[])
{
    int in_fd;
    int out_fd;
    int n_chars;
    char buffer[BUFFERSIZE];

    if (argc != 3)
    {
        fprintf(stderr,"usage:%s source destination/n",*argv);
        exit(1);
    }

    if ((in_fd = open(argv[1], O_RDONLY)) == -1)
        oop("cannot open", argv[1]);
    if ((out_fd = open(argv[2], O_RDONLY)) == -1)
        oop("cannot open", argv[2]);

    while ((n_chars = read(in_fd, buffer, BUFFERSIZE)) > 0)
        if (write(out_fd, buffer, n_chars) != n_chars)
            oop("write error to", argv[2]);

    if (n_chars == -1)
        oop("read error from", argv[1]);
    if (close(in_fd) == -1 || close(out_fd) == -1)
        oop("error closing files", "");

}

void oop(char *s1, char *s2)
{
    fprintf(stderr,"error:%s",s1);
    perror(s2);
    exit(1);
}