File Navigation with lseek in C/C++

Damien
3 min readAug 22, 2023

Today we will delve deeper into the field of file manipulation in C/C++ to with the lseek() function.

Iseek What?

When working with files in C/C++, you may encounter the challenge of accessing specific portions of a large file. This is precisely where the lseek() function becomes your ally. It allows you to move the read or write pointer inside a file, providing precise control over your operations.

The signature of the lseek() function is as follows:

off_t lseek(int fd, off_t offset, int whence);

fd: The file descriptor on which you want to perform the seek operation.
offset: The offset to apply relative to the reference position, measured in bytes.
whence: The reference position from which the offset is calculated. C

ommon values are SEEK_SET, SEEK_CUR, and SEEK_END, representing the beginning, current position, and end of the file respectively.

Navigating to a Specific Position in a File

Let’s say we have a file named “data.txt” containing structured data and we want to move it to a specific position for reading. Here’s how to use lseek() to achieve this:

#include <unistd.h>
#include <fcntl.h>

int main() {
int fileDesc = open("data.txt", O_RDONLY);
off_t position = 100; // Nouvelle position en octets

// Utilisation de lseek pour se déplacer à la position souhaitée
if (lseek(fileDesc, position, SEEK_SET) != -1) {
// Ici, nous sommes à la position 100
// Vous pouvez effectuer vos opérations de lecture ici
}

close(fileDesc);
return 0;
}

We start by accessing the “data.txt” file in a way that restricts us to read-only. Next, we use the lseek() function to move the read pointer to position 100 from the starting point of the file (`SEEK_SET`). With this adjustment complete, we are now ready to engage in reading activities from this new point.

Navigating to the Last Line of a Log File

Assume we have a log file named “journal.log” and we want to extract the last line. Here’s how to use lseek() to reach the end of the file and extract the line:

#include <unistd.h>
#include <fcntl.h>

int main() {
int fileDesc = open("data.txt", O_RDONLY);
off_t position = 100; // New position in bytes

// Using lseek to move to the desired position
if (lseek(fileDesc, position, SEEK_SET) != -1) {
// We are now at position 100
// You can perform your reading operations here
}

close(fileDesc);
return 0;
}

We initiate access to the log file “journal.log” in a mode that only permits reading. Through the utilization of the lseek() function, we shift the reading indicator towards the conclusion of the file (`SEEK_END`). Upon reaching this terminal point, we are enabled to peruse the content within the ultimate line.

Reading a Paragraph from a Text File

If we have a text file “sample.txt” with several paragraphs, and we want to extract and display the second paragraph. Here’s how you can achieve that:

#include <stdio.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#define BUFFER_SIZE 4096

int main() {
int fd = open("sample.txt", O_RDONLY);
char buffer[BUFFER_SIZE];
off_t position = 0;
int paragraphCount = 0;

// Traverse the file until the second paragraph
while (paragraphCount < 2) {
ssize_t bytesRead = read(fd, buffer, BUFFER_SIZE);
if (bytesRead == 0) {
break;
}

for (ssize_t i = 0; i < bytesRead; i++) {
if (buffer[i] == '\n') {
paragraphCount++;
if (paragraphCount == 2) {
position = lseek(fd, 0, SEEK_CUR);
break;
}
}
}
}

// Move to the beginning of the second paragraph
lseek(fd, position, SEEK_SET);
ssize_t bytesRead = read(fd, buffer, BUFFER_SIZE);
write(STDOUT_FILENO, buffer, bytesRead);

close(fd);
return 0;
}

We open the text file “sample.txt” in read-only mode. We loop through the file until we reach the second paragraph, counting the newline characters (`’\n’`). Once we have identified the position at the beginning of the second paragraph, we use lseek() to move there (`SEEK_SET`). Finally, we read and display the contents of this paragraph.

Kudos, you now have a firm understanding of lseek() in C/C++, a potent tool for file management. Bon voyage in the fascinating world of file manipulation in C/C++.

Photo by Jonathan Kemper on Unsplash

Sign up to discover human stories that deepen your understanding of the world.

Free

Distraction-free reading. No ads.

Organize your knowledge with lists and highlights.

Tell your story. Find your audience.

Membership

Read member-only stories

Support writers you read most

Earn money for your writing

Listen to audio narrations

Read offline with the Medium app

Damien
Damien

Written by Damien

5 minute articles!!! Between two coffee or tea you can read articles

No responses yet

Write a response