- #include <fcntl.h>
- #include <unistd.h>
- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #define BUFFER_SIZE 1024
- int main(int argc,char *argv[])
- {
- int from_fd,to_fd;
- struct stat buf_from[BUFFER_SIZE],buf_to[BUFFER_SIZE];
- char buffer[BUFFER_SIZE];
- int file_len = 0;
- if(argc != 3)
- {
- printf("Usage %s from_file to_file\\n",argv[0]);
- exit(EXIT_FAILURE);
- }
- if((from_fd = open(argv[1],O_RDONLY)) < 0)
- {
- perror("open from_file");
- exit(EXIT_FAILURE);
- }
- if((to_fd = open(argv[2],O_WRONLY | O_CREAT | O_TRUNC)) < 0)
- {
- perror("open to_file");
- exit(EXIT_FAILURE);
- }
- if(stat(argv[1],buf_from) < 0)
- {
- perror("stat from_file");
- exit(EXIT_FAILURE);
- }
- if(stat(argv[2],buf_to) < 0)
- {
- perror("stat to_file");
- exit(EXIT_FAILURE);
- }
- if(fchmod(to_fd,buf_from->st_mode) < 0)
- {
- perror("fchmod to_file");
- exit(EXIT_FAILURE);
- }
- file_len = lseek(from_fd,0L,SEEK_END)-lseek(from_fd,0L,SEEK_SET);
- printf("from file size is %d\\n",file_len);
- while(read(from_fd,buffer,BUFFER_SIZE) > 0)
- {
- if(BUFFER_SIZE > file_len)
- {
- if(write(to_fd,buffer,file_len) != file_len)
- {
- perror("write to_file error");
- exit(EXIT_FAILURE);
- }
- }
- else
- {
- if(write(to_fd,buffer,BUFFER_SIZE) != BUFFER_SIZE)
- {
- perror("write to_file error");
- exit(EXIT_FAILURE);
- }
- file_len = file_len - BUFFER_SIZE;
- }
- bzero(buffer,BUFFER_SIZE);
- }
- close(from_fd);
- close(to_fd);
- }
- //该片段来自于http://www.codesnippet.cn/detail/200620134180.html
来源: http://www.codesnippet.cn/detail/200620134180.html