shell / mycopy.c
mycopy.c
Raw
#include <sys/types.h>
#include <fcntl.h>
#include <stdlib.h>
#include <unistd.h>
#include <stdio.h>

#define BUF_SIZE 4096
#define OUTPUT_MODE 0666
#define TRUE 1

int main(int argc, char *argv[]) {
    
    int in_fd, out_fd, rd_count, wt_count;
    char buffer[BUF_SIZE];
    
    
    if (argc != 3){
        fprintf(stderr, "Error: Invalid number of arguments.\n");
        return EXIT_FAILURE;
    }
    
    
    in_fd = open(argv[1], O_RDONLY);
    if (in_fd < 0) {
        fprintf(stderr, "Error: File could not be opened.\n");
        return EXIT_FAILURE;
    }
    
    
    out_fd = open(argv[2], O_RDWR | O_TRUNC | O_CREAT, OUTPUT_MODE);
    if (out_fd < 0){
        fprintf(stderr, "Error: Copy could not be created.\n");
        return EXIT_FAILURE;
    }

    
    while (TRUE) {
        rd_count = read(in_fd, buffer, BUF_SIZE);
        if (rd_count <= 0) break;
        wt_count = write (out_fd, buffer, rd_count);
        if (wt_count <= 0){
            fprintf(stderr, "An error occured while copying the data.\n");
            return EXIT_FAILURE;
        }
        
    }
    
    close(in_fd);
    close(out_fd);
    if (rd_count == 0) return 0;
    else {
        fprintf(stderr, "An error occured while copying the data.\n");
        return EXIT_FAILURE;
    }
    
}