Javatpoint Logo
Javatpoint Logo

lseek() in C

In this article, we will discuss the lseek() function with its syntax, parameter, example, advantages, and disadvantages.

lseek () is a function in the C programming language that permits you to move the file pointer to a detailed position within a report. The record pointer represents the present-day function for analyzing or writing operations. Using lseek () function, you may alternate the location of the file pointer and carry out the next examination or write operations from that new role.

The operating system keeps track of the current location within a file using an internal data structure known as the file pointer in the C programming language. It designates the following byte to be read or written.

The fd, offset, and whence are the inputs the lseek() function requires. The File on which you want to run the seek operation is identified by its file descriptor or fd. Whence is the starting point from which the offset is determined, and offset is the number of bytes you want to relocate the file pointer.

The whence parameter can take one of the following values:

SEEK_SET (0): It sets the file pointer to the beginning of the file and provides the offset.

SEEK_CUR (1): It sets the file pointer to the current role and adds the offset.

SEEK_END (2): It sets the file pointer to the end of the file and provides the offset to it.

After calling lseek (), the file pointer is updated in keeping with the specified parameters. The return cost of lseek () is the resulting offset role from the beginning of the File, or -1, in case of errors.

Syntax:

In C, lseek() has the following syntax:

fd: The seek operation will be performed on the file specified by the file descriptor, or fd.

Offset: It is the number of bytes the file pointer should be moved.

whence: The starting point for the calculation of the offset.

Program:

Output:

Read 0 bytes:

Explanation:

This code snippet shows how to open a file, lseek a particular location in the File, read data, and print the results-basic file handling procedures. It also includes handling potential errors during these activities and closing the file descriptor that ensures proper resource management.

The code snippet demonstrates an accessible report managing an operation with the use of open(), lseek (), and read() functions in C. Let's summarize the general drift and motive of the code:

Header Files: The required header documents (stdio.h, fcntl.h, unistd.h, and errno.h) are included at the start of the code. These header files offer essential capabilities and definitions for file handling, input/output operations, and error handling.

Opening the File: The open() function is known to open the document named "example.txt" in study-best mode (O_RDONLY). If the File does not exist, the O_CREAT flag is utilized in aggregate with file permissions (0644) to create a brand-new document. The open() characteristic returns a file descriptor (fd) representing the opened record.

Error Handling for File Opening: If the open() feature fails (returns -1), a blunders message is outlined using error (), indicating the cause for the failure. After that, the program returns with non-0 popularity, indicating an error.

Seeking a Specific Position: The lseek () function is used to transport the file pointer to the 10th byte from the start of the record (SEEK_SET). The characteristic returns the ensuing offset role from the beginning of the report (offset).

Error Handling for Seeking: If the lseek() function fails (returns -1), an error message has been printed with the use of error (). The close() feature shuts the file descriptor (fd) to release the related sources. After that, the program returns with a non-zero repute, indicating a blunder.

Reading from the File: The read() function is used to examine statistics from the file into the individual array buffer. It reads files from the file descriptor (fd) into a buffer with a maximum length of sizeof(buffer).

Error Handling for Reading: If the read() function fails (returns -1), an error message has been printed with the use of error (). The close() function shuts the file descriptor (fd) to release the associated resources. After that, the program returns with a non-0 reputation, indicating a mistake.

Printing the Read Data: The program prints the variety of bytes study (bytes read) and the buffer's content using printf(). The %zd format specifier is used to print the value of bytesRead as a ssize_t type, and %.*s is used to print the buffer as a string with a variable period based totally on bytesRead.

Closing the File: The close() feature is known to close the file descriptor (fd) and release the related assets.

Successful Execution: The program exits with a standing of 0, indicating a hit execution.

Complexity Analysis:

The time and space complexity of the lseek () function in C can vary depending on the underlying file system, and they search for the operation being performed.

Time Complexity:

The lseek () feature's time complexity is commonly considered steady or close to-consistent time because it entails updating the file pointer function, which is usually a simple mathematics operation.

However, the real-time taken for seeking inside a record can depend on different factors, together with the document system implementation, disk getting right of entry to instances, file length, and searching for distance. Seeking inside a report may be a noticeably fast operation on contemporary record structures and hardware, particularly if the document is stored on a Solid State Drive (SSD) or if the files are searching for distance is small. Searching for a selected function within a report is considered an efficient operation.

Space Complexity:

The lseek () function's space complexity is considered constant because it requires no substantial additional memory allocation or information structures.

However, remember that the general space complexity of an application that uses lseek () may additionally rely upon other factors, including the scale of the record being accessed, the size of buffers used for reading or writing, and any extra facts structures hired inside the application.

It's essential to notice that the time and space complexity of different operations, including read() or write() that can be performed after the lseek () operation, can range and rely on elements unique to those operations.

The lseek() function's time complexity is commonly considered steady. In contrast, the overall time and spcae complexity of an application that uses lseek() function that depends on different factors related to file length, trying to find the distance, disk get entry to times, and different operations completed along lseek ().

Properties of lseek() in C :

Here are the important things houses of the lseek() function in C:

Repositioning the File pointer Pointer: The primary reason for lseek () is to reposition the inside of a file. It lets you move the file pointer to a specific function primarily based on an offset value and a reference point.

File Descriptor: The lseek () operates on a record already opened and accessed through a file descriptor. You want to offer the file descriptor acquired from capabilities like open() or creat() as the first argument to lseek ().

Offset and Reference Point: The offset parameter in lseek () specifies the number of bytes to transport the file pointer. It may be acceptable or poor, indicating movement ahead or backward. The whence parameter determines the reference factor for they are trying to find operation, which may be SEEK_SET (beginning of the document), SEEK_CUR (cutting-edge role), or SEEK_END (end of the report).

Return Value: The return value of lseek () is the resulting offset role from the document's start. If the trying-to-find operation is successful, it returns the brand-new offset position. Otherwise, it returns -1 to suggest a mistake.

File System Limitations: The operation of lseek () may be tormented by obstacles imposed by the underlying document gadget. For instance, a few record systems won't support looking past the end of a file or may also have restrictions on most searching for distance.

Effect on Read/Write Operations: The lseek () function does no longer, without delay, carry out read or write operations. Instead, it positions the file pointer, determining the subsequent examine or write operations at the file. After searching for a selected role, you may carry out read or write operations using functions like read() or write() to get admission to the facts in that vicinity.

File Types: The lseek () may be used with various files, including regular files, character gadgets, block devices, etc. The behavior of lseek() can also range depending on the sort of document being operated on.

Error Handling: Like different system calls, lseek () can get stuck upon errors. In case of an error, lseek () sets the global variable errno to a specific error code, which can be accessed using the error () function to print an error message.

The lseek () function gives a bendy and effective mechanism to reposition the record pointer inside a document, permitting green random get right of entry to and manipulation of record statistics in C programs.

Advantages:

There are various advantages of lseek() function in C. Some main advantages of lseek() function are as follows:

Random Access: The lseek () function enables random access to particular file elements. It lets you set the document pointer to any favored position inside the file, no matter the cutting-edge position. This random get admission to capability is helpful for programs that need to read or adjust precise quantities of a report efficaciously.

Efficient Large File Handling: The lseek () can manage files of big sizes while not having to examine the whole report sequentially. It lets you leap at once to the favored function, which is especially useful while managing documents that are too huge to suit entirely into reminiscence.

Efficient File Truncation: The lseek () can be combined with the O_TRUNC flag within the open() feature to truncate a report to a specific size. By in search of to a preferred position and then starting the file with O_TRUNC, you can efficiently truncate the record to the preferred length without having to rewrite the entire record.

Integration with File Locking: The lseek () can be used along with file locking mechanisms and fcntl() with F_SETLK or F_SETLKW to govern concurrent get entry to particular file regions. By setting the file pointer and acquiring suitable locks, you could enforce synchronization and save your facts corruption in multi-system or multi-threaded environments.

Disadvantages and Considerations:

There are various disadvantages of lseek() function in C. Some main disadvantages of lseek() function are as follows:

Limited to File I/O: The lseek () function is unique to file input/output (I/O) operations. It cannot be used to seek within other information systems like arrays or memory buffers. Alternative mechanisms must be applied if random access is required inside such structures.

Dependency on File Position: The lseek () function manipulates the file pointer without any delay, which can introduce complexity and potential pitfalls in multi-threaded or concurrent programming environments.

File System Dependency: The behavior of lseek () can vary throughout unique file structures. Some document structures might also have obstacles at the maximum seeking distance, or the operation can be distinctive for particular document types, including user gadgets or network sockets.

Error Handling: It is critical to address errors effectively when the usage of lseek(). Errors can occur due to the file getting the rights of entry to permissions, looking past the document length, or other factors. Please address errors to avoid unexpected behavior or statistics corruption.

Sequential Access Efficiency: While lseek() function permits random get right of entry to within a file, it is optimized for sequential get admission. If you must carry out multiple non-sequential seeking operations or frequent lower back-and-forth moves, the performance may also degrade compared to sequential reading or writing.

Inconsistent Behaviour for Certain File Types: The behavior of lseek () function can be inconsistent for certain types of files, including user gadgets or community sockets. These types of documents frequently have specialized operations and different ways of gaining access to data, which may not conform to the same old file pointer conduct related to seek ().







Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA