// Linux File programming--file_cp.c in the system file call
// To be modified...
1 # include <stdio. h> 2 # incldue <sys/STAT. h> 3 # include <fcntl. h> 4 # include <errno. h> 5 6 # define buffsize 1024 7 8 int main (INT argc, char * argv []) 9 {10 int from_fd, to_fd; 11 int bytes_read, bytes_write; 12 char buffer [buffsize]; 13 char * PTR; 14 15 if (argc! = 3) 16 {17 fprintf (stderr, "Usage: % s from_file to_file \ n", argv [0]); 18 exit (exit_failure ); 19} 20 21 // open from_file22 if (from_fd = open (argv [1], o_rdonly) =-1) 23 {24 fprintf (stderr, "Open % s error: % s \ n", argv [1], strerror (errno); 25 exit (exit_failure ); 26} 27 // creat to_file28 if (to_fd = open (argv [2], o_wronly | o_creat, s_irusr | s_iwusr) =-1) 29 {30 fprintf (stderr, "Open % s error: % s", argv [2 ], Strerror (errno); 31 exit (exit_failure); 32} 33 34 // classic copy file code 35 while (bytes_read = read (from_fd, buffer, buffsize )) 36 {37 If (bytes_read =-1) & (errno! = Eintr) break; 38 else if (bytes_read> 0) 39 {40 PTR = buffer; 41 while (bytes_write = write (to_file, buffer, bytes_read )) 42 {43 // a fatal error occurs 44 If (bytes_write =-1) & (errno! = Eintr) break; 45 // After writing all the read bytes, 46 else if (bytes_write = bytes_read) break; 47 // only write a part, continue to write 48 else if (bytes_write> 0) 49 {50 PTR + = bytes_write; 51 bytes_read-= bytes_write; 52} 53} 54 // An error occurred while writing 55 if (bytes_write =-1) break; 56} 57} 58 close (from_fd); 59 close (to_fd ); 60 exit (0); 61}
File programming file_copy.c