Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Iseek() in C/C++ to read the alternate nth byte and write it in another file
The lseek() function in C is used to change the file offset (position) of the file descriptor. It allows us to read data from specific positions in a file by moving the file pointer. In this tutorial, we'll demonstrate how to read alternate nth bytes from one file and write them to another file.
Note: This program requires file I/O operations with system calls that may not work in all online compilers. Create "start.txt" with sample content before running.
Syntax
off_t lseek(int fd, off_t offset, int whence);
Parameters
- fd − File descriptor
- offset − Number of bytes to move
- whence − Position reference (SEEK_SET, SEEK_CUR, SEEK_END)
Example: Reading Alternate nth Bytes
This example reads every 5th byte from "start.txt" and writes it to "end.txt" −
#include <stdio.h>
#include <unistd.h>
#include <sys/types.h>
#include <fcntl.h>
void readAlternateBytes(int n) {
int f_read = open("start.txt", O_RDONLY);
int f_write = open("end.txt", O_WRONLY | O_CREAT, 0644);
char buffer[1];
if (f_read == -1 || f_write == -1) {
printf("Error opening files\n");
return;
}
// Read every nth byte
while (read(f_read, buffer, 1) == 1) {
write(f_write, buffer, 1);
// Skip next n-1 bytes
lseek(f_read, n-1, SEEK_CUR);
}
close(f_read);
close(f_write);
}
int main() {
int n = 5; // Read every 5th byte
readAlternateBytes(n);
printf("Alternate bytes copied successfully\n");
return 0;
}
How It Works
-
open()opens files with specified modes (O_RDONLY for reading, O_WRONLY for writing) -
read()reads one byte at a time from the source file -
lseek()with SEEK_CUR moves the file pointer n-1 positions forward -
write()writes the byte to the destination file -
close()closes both file descriptors
Example File Content
If "start.txt" contains: ABCDEFGHIJKLMNOP
And n=5, then "end.txt" will contain: AFKP (every 5th character)
Key Points
- Always check if file operations succeed by verifying return values
- Use proper file permissions when creating files with O_CREAT
- Close file descriptors to free system resources
- SEEK_CUR moves relative to current position
Conclusion
The lseek() function provides precise control over file positioning, enabling efficient reading of specific byte patterns. This technique is useful for parsing structured binary files or extracting data at regular intervals.
