Linux/쉘, 쉘 명령어 구현하기

[쉘 구현하기] cp 명령어 구현

Study with Me! 2023. 8. 14. 22:56

첫 번째 인자 파일을 두 번째 인자 파일에 복사하는 cp 명령어를 추가했다.

코드는 복잡하진 않았다.

첫 번째 인자의 파일 디스크립터(fd1)로부터 내용을 읽어서 두 번째 인자의 파일 디스크립터(fd2)로 쓰는 작업을 진행했다. 파일을 읽는 과정은 파일의 끝(EOF)을 읽을 때까지 반복된다.

// my_cp.c
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#define BUFFER_SIZE 4096
#define PATH_MAX 4096

void cp(int argc, char **argv) {
    int fd1, fd2;
    char buf[BUFFER_SIZE]; int length;

    if (argc < 3) {
        fprintf(stderr, "Usage: %s <FILENAME1> <FILENAME2>\n", argv[0]);
        exit(1);
    }

    if ((fd1 = open(argv[1], O_RDONLY)) < 0) {
        fprintf(stderr, "open error for %s\n", argv[1]);
        exit(1);
    }

    if ((fd2 = open(argv[2], O_WRONLY | O_CREAT | O_TRUNC, 0644)) < 0) {
        fprintf(stderr, "open error for %s\n", argv[2]);
        exit(1);
    }

    while (1) {
        if ((length = read(fd1, buf, BUFFER_SIZE)) < 0) {
            fprintf(stderr, "read error\n");
            exit(1);
        }
        else if (length == 0) break;

        write(fd2, buf, length);
    }

    close(fd1);
    close(fd2);
    exit(0);
}

위 코드는 아래 이미지를 클릭해 깃허브에서도 확인할 수 있다.

깃허브 이미지 링크