File programming file_copy.c

Source: Internet
Author: User
// 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

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.