|
APUE2习题4.6:编写一个类似cp的程序,它复制包含空洞的文件,但不将字节0写到输出文件中去。
我写的这个程序对于4096字节下的文件复制有效,但是大于4096的文件就会复制有误,大家帮忙看看,程序代码如下:
#include "apue.h"
#include <fcntl.h>
#define BUFFSIZE 4096
int
main(int argc, char * argv[])
{
int fd1,fd2, currpos, num_read;
currpos = 0;
char buf[BUFFSIZE];
if (argc != 3)
err_sys("usage:./a.out <input file> <output file>");
if ((fd1 = open(argv[1], O_RDWR)) < 0)
err_sys("open error for %s", argv[1]);
if (lseek(fd1, currpos, SEEK_CUR) < 0)
err_sys("lseek error for %s", argv[1]);
if ((fd2 = creat(argv[2], FILE_MODE)) < 0)
err_sys("creat error for %s", argv[2]);
if (lseek(fd2, currpos, SEEK_CUR) < 0)
err_sys("lseek error for %s", argv[2]);
while(1)
{
if ((num_read = read(fd1, buf, BUFFSIZE)) < 0)
err_sys("read error for %s", argv[1]);
if (num_read == 0)
break;
if (write(fd2, buf, num_read) != num_read)
err_sys("write error for %s", argv[2]);
currpos += num_read;
if (lseek(fd1, currpos, SEEK_CUR) < 0)
err_sys("lseek error for %s", argv[1]);
if (lseek(fd2, currpos, SEEK_CUR) < 0)
err_sys("lseek error for %s", argv[2]);
}
exit(0);
} |
|