Linux C 中 open close read write 使用实例

这里实现的是将文件cody.txt中的内容拷贝到to_cody.txt中去。



1
/* 2 ============================================================================ 3 Name : FileIO.c 4 Author : Cody 5 Version : 6 Copyright : Written By Cody 7 Description : 8 ============================================================================ 9 */ 10 11 #include <stdio.h> 12 #include <stdlib.h> 13 #include <string.h> 14 15 16 #include <sys/types.h> 17 #include <sys/stat.h> 18 #include <fcntl.h> 19 20 #include <unistd.h> 21 22 int main(int argc,char *argv[]) { 23 24 int fromFd = open("/root/cody.txt",O_RDONLY); 25 if(fromFd == -1) 26 { 27 perror("打开From文件"); 28 exit(0); 29 } 30 31 int toFd = open("/root/to_cody.txt",O_WRONLY | O_CREAT); 32 if(toFd == -1) 33 { 34 perror("打开To文件"); 35 exit(0); 36 } 37 38 read_To_File(fromFd,toFd); 39 40 close(fromFd); 41 close(toFd); 42 43 return EXIT_SUCCESS; 44 } 45 46 47 /** 48 * 将一个文件的内容,写入到另一个文件 49 */ 50 int read_To_File(int fromFd,int toFd) 51 { 52 53 char buf[512]; 54 55 int readBytes; 56 57 int writeBytes; 58 59 if(fromFd == -1 || toFd == -1) return -1; 60 61 memset(buf,0,sizeof(buf)); 62 printf("开始读写\n"); 63 while((readBytes = read(fromFd,buf,sizeof(buf))) > 0) 64 { 65 puts(buf); 66 67 writeBytes = write(toFd,buf,readBytes); 68 69 if(writeBytes == -1) 70 { 71 perror("write error"); 72 } 73 74 memset(buf,0,sizeof(buf)); 75 } 76 77 return 1; 78 }

 

你可能感兴趣的:(linux)