2013-10-19 21 views
0

我有一个while循环,我正在从档案文件中读取并提取第一个文件。C读写问题w /指定的字节长度

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 

预期的输出应该是一个文件,“文件1”只包含内容“是testing123”。 相反,我得到文件1与内容: 测试123

File2    1382142504 501 20 100644 23  ` 
Testing 246 

出于某种原因,即使我指定位的数量读写(参数3是“大小”返回29 - File1)的大小,它保持读取和写入超过29个字节。

任何想法,为什么会发生这种情况?

回答

1

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

你需要在循环中更新的大小。

size -= n_read

否则你只是要继续循环,直到你到达文件的末尾。你需要循环调用read()的原因只是它不能保证它会在第一次调用时读取指定的字节数,它只能保证它不会超过这个值。所以你需要不断地调用它,直到你阅读了所有你想要的字节。但是您确实需要更新字节参数,因为文件描述符fd将继续前进到文件末尾。