관리 메뉴

개발 노트

10/13 동시에 2개 파일로 복사하는 코드, 앞 내용 절반 뒷 내용 절반씩 나누어 복사하는 코드 본문

학부 공부 : 20.08.31~12.10/Linux

10/13 동시에 2개 파일로 복사하는 코드, 앞 내용 절반 뒷 내용 절반씩 나누어 복사하는 코드

hayoung.dev 2020. 10. 14. 11:37

1. copy3.c : a.txt를 b.txt c.txt로 동시에 2개의 파일로 복사하는 프로그램

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>

int main(int argc, char **argv)
{
        int n, in, out1, out2;
        char buf[1024];

        char *msg = "Usage : copy3 file1 file2 file3\n";
        if (argc < 4) {
                write(2, msg, strlen(msg));
                return -1;
        }
        if ((in = open(argv[1], O_RDONLY)) < 0) {
                perror(argv[1]);
                return -1;
        }
        if ((out1 = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) < 0) {
                perror(argv[2]);
                return -1;
        }
        if ((out2 = open(argv[3], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) < 0) {
                perror(argv[3]);
                return -1;
        }

        while ((n = read(in, buf, sizeof(buf))) > 0) {
                write(out1, buf, n);
                write(out2, buf, n);
        }
        close(out2);
        close(out1);
        close(in);

        return 0;
}

2. copyh.c : a.txt의 내용 앞 절반을 b.txt에 나머지를 c.txt로 동시에 2개의 파일로 복사하는 프로그램

#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <sys/stat.h>
#include <sys/types.h>
#include <string.h>
#include <stdlib.h>

int main(int argc, char **argv)
{
        int n, in, out1, out2;
        char buf[1];
        struct stat sb;

        char *msg = "Usage : copyh orig firsthalf lastalf\n";
        if (argc < 4) {
                write(2, msg, strlen(msg));
                return -1;
        }
        if ((in = open(argv[1], O_RDONLY)) < 0) {
                perror(argv[1]);
                return -1;
        }
        if (fstat(in, &sb) == -1) {
                perror("stat");
                exit(EXIT_FAILURE);
        }
        printf("File size: %lld bytes\n", (long long) sb.st_size);	// sb.st_size 가 우리가 알려는 사이즈

        if ((out1 = open(argv[2], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) < 0) {
                perror(argv[2]);
                return -1;
        }
        if ((out2 = open(argv[3], O_WRONLY|O_CREAT|O_TRUNC, S_IRUSR|S_IWUSR)) < 0) {
                perror(argv[3]);
                return -1;
        }

        int cnt = 0;
        while ((n = read(in, buf, sizeof(buf))) > 0) {
                if(cnt < (sb.st_size/2))
                        write(out1, buf, n);
                else
                        write(out2, buf, n);

                cnt=cnt+n;
                printf("%d ", cnt);
        }

        close(out2);
        close(out1);
        close(in);

        return 0;
}

 

반응형