C/C++ (Window) Buffer to File, File to Buffer

Here is the sample code to:
+read and copy the content of the file into a buffer
+create a new file, then copy the content of the buffer into a new file


while (1) {
   int src_fld = open("C:\test.txt", O_RDONLY);//return src_fld as unique file handle
   int error = read(src_fld, buffer, 1024);//read the file for 1024 bytes and put to buffer

   if (error == -1) {//error=-1 for error | error=0 for EOL | error = number of byte  
     printf("Error reading SRC file.\n");
     exit(1);
   }
   n = error;
   if (n == 0) break;

   int dst_fld = open("C:\test2.txt", O_CREAT | O_WRONLY);
   error = write(dst_fld, buffer, n);//write n bytes from buffer to dst_fld
   if (error == -1) {
      printf("Error backup to DEST.\n");
      exit(1);
   }
}

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.