lseek() in C/C++ to read the alternate nth byte and write it in another file
From a given file (e.g. input.txt) read the alternate nth byte and write it on another file with the help of “lseek”.
lseek (C System Call): lseek is a system call that is used to change the location of the read/write pointer of a file descriptor. The location can be set either in absolute or relative terms.
Function Definition
off_t lseek(int fildes, off_t offset, int whence);
Field Description
int fildes : The file descriptor of the pointer that is going to be moved
off_t offset : The offset of the pointer (measured in bytes).
int whence : The method in which the offset is to be interpreted
(rela, absolute, etc.). Legal value r this variable are provided at the end.
return value : Returns the offset of the pointer (in bytes) from the
beginning of the file. If the return value is -1,
then there was an error moving the pointer.
For example, say our Input file is as follows:
#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 file (end.txt)
Last Updated :
07 Feb, 2018
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...