Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                

Iseek in C/C++ to Read Alternate Nth Byte and Write it in Another File



In this tutorial, we will be discussing a program to understand how to read the alternate nth byte and write it in another file.

For this, we will be provided with two .txt files. Our task is to write the contents from one file to another file using Iseek() which is used to change the pointer of the file descriptor.

Example

#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void func(char arr[], int n){
   int f_write = open("start.txt", O_RDONLY);
   int f_read = open("end.txt", O_WRONLY);
   int count = 0;
   while (read(f_write, arr, 1)){
      if (count < n) {
         lseek (f_write, n, SEEK_CUR);
         write (f_read, arr, 1);
         count = n;
      }
      else{
         count = (2*n);
         lseek(f_write, count, SEEK_CUR);
         write(f_read, arr, 1);
      }
   }
   close(f_write);
   close(f_read);
}
int main(){
   char arr[100];
   int n;
   n = 5;
   func(arr, n);
   return 0;
}

Output

(First file) 

 (Output file) 

Updated on: 2020-04-01T06:38:41+05:30

674 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements