프로그래밍

 3198, 1/160 회원가입  로그인  
   pimngee
   [C언어]연산 과정좀 설명해주세요..

http://www.hackerschool.org/HS_Boards/zboard.php?AllArticle=true&no=3255 [복사]


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

#define MAXLINE 512
int main(int argc, char **argv)
{
        int source_fd;
        int dest_fd;
        int readn;
        int totaln=0;
        char buf[MAXLINE];

        if (argc != 3)
        {
                fprintf(stderr, "Usage : %s [source file] [dest file]\n", argv[0]);
                return 1;
        }
        if( !(source_fd = open(argv[1], O_RDONLY)) )
        {
                perror("Error ");
                return 1;
        }
        if( !(dest_fd = open(argv[2], O_CREAT|O_EXCL|O_WRONLY,
                                S_IRUSR|S_IWUSR|S_IRGRP|S_IROTH)) )
        {
                perror("Error ");
                return 1;
        }
        if (errno == EEXIST)
        {
                perror("Error ");
                close(dest_fd);
                return 1;
        }

        memset(buf, 0x00, MAXLINE);
        while((readn = read(source_fd, buf, MAXLINE)) > 0)
        {
                printf("readn : %d\n", readn);
                totaln+=write(dest_fd, buf, readn);
                memset(buf, 0x00, MAXLINE);                        
        }
        printf("Total Copy Size : %d\n", totaln);
        return 0;
}



결과가

readn : 512
readn : 483
Total Copy Size : 995 로 나옵니다.

왜 이렇게 되는거죠..

  Hit : 5877     Date : 2011/12/22 07:30



    
key 총 파일 사이즈가 995 이고, read() 함수에서 MAXLINE인 512바이트만큼 읽으니까 두 번에 걸쳐서 읽게 되겠죠?
512 만큼읽고, 그 다음 512만큼 읽어서(두번째 읽은 리턴 값은 483) readn : 값 이 두번 출력되고 토탈은 995가 출력됩니다.
2011/12/22  
pimngee 죄송합니다. C언어를 공부한지가 오래되서 말도안되는 질문일수도 있습니다만..

두번에 걸쳐서 읽는데 파일이 하나로 복사가 어떻게 되는거죠?
그리고 buf 계산은 오픈명령어 뒤에있는데요...

질문이 이상한거같지만.. 정확히 어떻게 물어봐야할지 모르겠네요.. 책을봐도 정형적인 글들뿐이고...
2011/12/22  
pimngee 아니면 open에 의해서 앞에서 복사된 후에

뒤에 프린트문은 용량 계산만 하는건가요?
2011/12/22  
pimngee 아 ㅋ 시간좀 지나고 보니까 이해가 되네요.
바보같은 질문이나하고. 감사합니다 ㅋㅋ
2011/12/22