2013-10-19 5 views
0

나는 보관 파일에서 읽고 첫 번째 파일을 추출하는 while 루프가 있습니다. 구조에 주어진 아카이브 파일의 경우C 읽기 및 쓰기 문제 지정된 바이트 길이로

int fd = open(argv[2], O_RDWR | O_CREAT, 0666); 
    char name_buffer[16]; 
    char size_buffer[10]; 

    // go to the first header 
    lseek(fd, SARMAG, SEEK_CUR); 

    // store the number of bits read in a struct current_header 
    // until its size equal to the size of the entire 
    // header, or in other words, until the entire 
    // header is read 
    while ((num_read = read(fd, (char*) &current_header, 
    sizeof(struct ar_hdr))) == sizeof(struct ar_hdr)) 
    { 

    // scans the current string in header and stores 
    // in nameStr array 
    sscanf(current_header.ar_name, "%s", name_buffer); 
    sscanf(current_header.ar_date, "%s", date_buffer); 
    sscanf(current_header.ar_uid, "%s", uid_buffer); 
    sscanf(current_header.ar_gid, "%s", gid_buffer); 

    int mode; 
    sscanf(current_header.ar_mode, "%o", &mode); 
    sscanf(current_header.ar_size, "%s", size_buffer); 
    sscanf(current_header.ar_fmag, "%s", fmag_buffer); 

    new_file_fd = open(name_buffer, O_WRONLY | O_CREAT | O_TRUNC); 
    int size = atoi(size_buffer); 
    char buf[size]; 
    size_t count = size; 

    while ((n_read = read(fd, buf, size)) > 0) 
    { 
     n_write = 0; 
     do { 
     n = write(new_file_fd, &buf[n_write], n_read - n_write); 
     n_write += n; 
     } while (n_write < n_read); 

    } 
    close(new_file_fd); 
    } 
    lseek(fd, size + (size%2), SEEK_CUR); 

:

!<arch> 
File1    1382142494 501 20 100644 29  ` 
Testing 123 

File2    1382142504 501 20 100644 23  ` 
Testing 246 

이 예상 출력 내용 만 "Testing123"를 포함하는 파일 "을 File1"이어야합니다. 는 대신,이 내용으로하며 File1 얻을 : 테스트 123

내가 (매개 변수 3은 29을 반환합니다 "크기"입니다 읽고 쓸 비트의 양을 지정한 경우에도 어떤 이유
File2    1382142504 501 20 100644 23  ` 
Testing 246 

- File1의 크기) 29 바이트를 초과하여 읽고 계속 유지합니다.

왜 이런 일이 일어날 수 있으리라 생각하십니까?

답변

1

while ((n_read = read(fd, buf, size)) > 0)

당신은 루프 내에서 크기를 업데이트해야합니다.

size -= n_read

그렇지 않으면 당신은 당신이 파일의 끝에 도달 할 때까지 반복 계속 될 것입니다. read()에 대한 호출을 반복해야하는 이유는 첫 번째 호출에서 지정된 바이트 수를 읽지 않는다는 것입니다. 단지 초과하지 않을 것입니다. 따라서 원하는 모든 바이트를 읽을 때까지 계속 호출해야합니다. 그러나 파일 설명자 fd은 파일의 끝까지 계속 진행하므로 bytes 매개 변수를 업데이트해야합니다.