cp

윤강훈·2024년 10월 12일

System Programming

목록 보기
3/12

cp

  • 파일이나 디렉토리 복사하는 명령어(파일 생성 -> 데이터 쓰기)

creat

  • 파일 생성 함수
#include <fcntl.c>

int creat(cont char *pathname, mode_t mode) {
	return open(path, O_WRONLY|O_CRAET|O_TRUNC, mode);
} // open 함수를 내부에서 호출
-> 성공 시 file descriptor 리턴, 실패 시 -1 리턴

write

  • 파일 쓰기 함수
#include <unistd.h>

ssize_t write(int fd, const void *buf, size_t nbytes);
-> 성공 시 실제 파일에 쓴 byte 수 리턴, 실패 시 -1 리턴
  • fd: file descriptor
  • buf: 데이터가 저장된 버퍼의 주소
  • nbytes: 저장할 바이트 수

cp 명령어 동작 과정

  1. 읽어올 파일 열기
  2. 쓸 파일 열기
  3. 버퍼에 읽어오기
  4. 버퍼에 있는 거 쓰기
  5. 3,4 반복 후 EOF 만나면 파일 닫기

code

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

#define BUFFERSIZE 1024
#define COPYMODE 0644

void oops(char*, char*);

int main(int ac, char *av[]){
	int in_fd, out_fd, n_chars, res=0;
	char buf[BUFFERSIZE];

	if (ac != 3){
		fprintf(stderr, "usage: %s source destination\n", *av);
		exit(-1);
	}
	if ((in_fd = open(av[1], O_RDONLY)) == -1){
		oops("Cannot open ", av[1]);
	}
	if ((out_fd = creat(av[2], COPYMODE))==-1){
		oops("Cannot creat", av[2]);
	}

	while ((n_chars = read(in_fd, buf, BUFFERSIZE))>0){
		if (write(out_fd, buf, n_chars) != n_chars){ // 읽어온 것과 쓴 것의 byte수가 다르면 오류 출력
			oops("Write error to ", av[2]);
		}
		else{
			res += n_chars;
		}
	}
	printf("total read bytes: %d\n", res);

	if (n_chars == -1){
		oops("Read error from ", av[1]);
	}
	if (close(in_fd) == -1 || close(out_fd) == -1){
		oops("Error closing files","");
	}
}

void oops(char *s1, char *s2){
	fprintf(stderr, "Error: %s", s1);
	perror(s2);
	exit(-1);
}
  • open: 파일 열기(O_RDONLY)
  • creat: 파일 생성(COPYMODE 0644)
  • read 함수로 읽고 버퍼에 저장
  • wirte 함수로 생성된 파일에 buf에 담긴 내용 쓰기
profile
Just do it.

0개의 댓글