最近学习linux下的C编程,不带缓存的文件I/O操作,主要是open(),read(),write(),lseek(),close()五个函数的使用
写了一个文件拷贝程序
代码如下:
View Code
1 //文件名:file_backup.c 2 //作者:yhc 3 //日期: 4 //程序说明:文件备份程序,linux下C编程,不带缓存的文件I/O操作,open(),read(),write(),lseek(),close()五个函数的使用 5 //程序功能:对输入的文件名进行备份,备份后的文件名为“原文件名+_backup“,并打印出文件的大小 6 7 #include <stdio.h> 8 #include <stdlib.h> 9 #include <string.h> 10 11 #include <sys/types.h> 12 #include <sys/stat.h> 13 #include <fcntl.h> 14 #include <unistd.h> 15 16 #define BUFFER_SIZE 1024 17 18 int main(int argc,char *argv[]) 19 { 20 int fd_file,fd_backfile; 21 int size_read,size_write,size_file; 22 char buf[BUFFER_SIZE]; 23 char backfile_name[50]; 24 25 //检测是否有输入要备份的文件名 26 if(argc < 2) 27 { 28 printf("please input the file name!\n"); 29 exit(1); 30 } 31 32 //备份文件的文件名为“原文件名+_backup“ 33 strcpy(backfile_name,argv[1]); 34 strcat(backfile_name,"_backup"); 35 36 //打开原文件 37 if((fd_file = open(argv[1],O_CREAT|O_RDWR,0666)) < 0) 38 { 39 perror("open error"); 40 exit(1); 41 } 42 43 //创建备份文件 44 if((fd_backfile = open(backfile_name,O_CREAT|O_RDWR,0666)) < 0) 45 { 46 perror("creat error"); 47 exit(1); 48 } 49 50 //复制原文件数据到备份的文件中 51 do 52 { 53 if((size_read = read(fd_file,buf,BUFFER_SIZE)) < 0) 54 { 55 //读取原文件的数据到缓冲区 56 perror("read error"); 57 exit(1); 58 } 59 60 if((size_write = write(fd_backfile,buf,size_read)) < 0) 61 { 62 //将缓冲区中的数据写入到备份文件中 63 perror("write error"); 64 exit(1); 65 } 66 67 }while(size_read == BUFFER_SIZE);//如果取到的size_read与缓存大小一样,说明还有数据需要复制,如果不一样说明复制结束,结束循环 68 69 //获取原文件的大小并打印出来 70 size_file=lseek(fd_file,0,SEEK_END); 71 printf("The size of %s is: %d Byte\n",argv[1],size_file); 72 printf("Backup file success!\n"); 73 74 //关闭文件 75 if(close(fd_file) < 0) 76 { 77 perror("close error"); 78 exit(1); 79 } 80 81 if(close(fd_backfile) < 0) 82 { 83 perror("close error"); 84 exit(1); 85 } 86 87 exit(0); 88 }
运行结果:




浙公网安备 33010602011771号