#include <stdio.h> #include <sys/stat.h> #include <fcntl.h> #include <unistd.h> #include <string.h> #include <errno.h> #define BUF_SIZE 1024 void cp(char *filename1, char *filename2) { int fd1 = open(filename1, O_RDONLY); if (fd1 == -1) { printf("fail to open %s:%s ", filename1, strerror(errno)); return; } int fd2 = open(filename2, O_WRONLY | O_APPEND | O_CREAT, 0664); char szBuf[BUF_SIZE]; int bytes; while(1) { memset(szBuf, 0, BUF_SIZE); bytes = read(fd1, szBuf, BUF_SIZE); if (bytes == 0) { break; } write(fd2, szBuf, bytes); } } int main(int argc, char **argv) { if (argc != 3 || !strcmp(argv[1], "--help")) { printf("Usage:%s [Src] [Dest] ", argv[0]); printf(" Src:Source file "); printf(" Dest:Destin file "); return 0; } cp(argv[1], argv[2]); return 0; }
待加强:如果要复制一个包含空洞(连续的空字节)的普通文件,并且要求目标文件的空洞与源文件保持一致。