Iseek() in C/C++ to read the 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: 01-Apr-2020

455 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements