- 论坛徽章:
- 0
|
下面是一个拷贝文件的函数,编译时也没有报错,但是却读不出数据
我调试过了,在执行while((read_size = read(from_fd, buff, BUFF_SIZE)) > 0 )时,直接跳到close了,求高手指教,实在弄不明白- #include <stdio.h>
- #include <stdlib.h>
- #include <sys/types.h>
- #include <sys/stat.h>
- #include <fcntl.h>
- #include <unistd.h>
- #define CREATE_MODE 0755
- #define BUFF_SIZE 1024
- int open_file(char *filename);
- void rw_file(int from_fd, int to_fd, char *src_file, char *det_file);
- int main(int argc, char *argv[]){
- int i = 0;
- char *src_file;
- char *det_file;
- int from_fd;
- int to_fd;
- if(argc < 3){
- perror("You haven't input the filename ,please try again!\n");
- exit(EXIT_FAILURE);
- }else{
- src_file = argv[1];
- det_file = argv[2];
- from_fd = open_file(src_file);
- to_fd = open_file(det_file);
- rw_file(from_fd, to_fd, src_file, det_file);
- // rw_file(open(argv[1]), open(argv[2]));
- }
- exit(EXIT_SUCCESS);
- return 0;
- }
- int open_file(char *filename){
- int fd = 0;
- if((fd = open(filename, O_WRONLY | O_CREAT, S_IRUSR | S_IWUSR | S_IXUSR))<0){
- printf("open file %s failure!\n",filename);
- exit(EXIT_FAILURE);
- }else{
- printf("open file %s success, fd:%d\n",filename,fd);
- }
- // if(close(fd) == 0){
- //
- // printf("close file %s success,fd:%d\n",filename,fd);
- // }else{
- // printf("close file %s failure,fd:%d\n",filename,fd);
- // }
- return fd;
- }
- void rw_file(int from_fd, int to_fd, char *src_file, char *det_file){
- int read_size = 0;
- int write_size = 0;
- char buff[BUFF_SIZE] = { 0 };
- while((read_size = read(from_fd, buff, BUFF_SIZE)) > 0 ){
- if(read_size == -1){
- break;
- }
- printf("read file %s success,from_fd:%d,read_size:%d",src_file,from_fd,read_size);
- write_size = write(to_fd, buff, read_size);
- while(write_size < read_size){
- read_size -= write_size;
- write_size += write(to_fd, buff, read_size);
- printf("write file %s success,to_fd:%d,write_size:%d",det_file,to_fd,write_size);
- }
- }
- close(from_fd);
- close(to_fd);
- return;
- }
复制代码 |
|