Fseek Vs Rewind In C

The fseek function within the C programming language is employed to reposition the file position indicator to a specified location within a file, often referred to as the file pointer. It allows you to adjust the location for the subsequent read or write action within the file. This function is a part of the C Standard Library, extensively utilized alongside file streams (FILE pointers) for performing file-related tasks.

The functionality of the fseek function within the C Standard Library can differ notably across various systems or implementations. Nevertheless, the primary objective and behavior of the function remain consistent with the C standard.

The fseek function modifies the file position indicator of the given file stream to a designated position. Every file stream includes a file position indicator that specifies the location for the next read or write operation within the file.

Syntax:

The fseek syntax is as follows:

Example

int fseek(FILE *stream, long offset, int origin);

Parameters:

A reference to a FILE object that represents the intended file stream.

The offset denotes the quantity of bytes by which the file pointer needs to shift. Its value can be positive or negative, depending on the direction of the movement.

The origin serves as the initial reference point for applying the offset. You can utilize any of the three values listed below for this purpose:

Example

int fseek(FILE *stream, long offset, int origin);
Example

int fseek(FILE *stream, long offset, int origin);

SEEK_END (2): It is relative to the file's end .

Return value:

If the process completes without issues, it will yield a return value of 0. Conversely, in case of an error, a non-zero value will be returned.

The fseek function provides an integer outcome to signal the success or failure of the operation. It gives back 0 upon successful completion, while a non-zero value is returned for unsuccessful attempts. In cases of errors, additional details can be obtained by referencing the errno variable or the error function.

It is crucial to keep in mind that the behavior of the fseek function is reliable only with binary files. Owing to differences in line-ending conventions across various operating systems, employing fseek on text files with variable-length line endings can lead to unexpected outcomes. It is generally recommended to utilize functions such as fgetc or fgets to extract data from a particular line in text files.

Program:

Here is a sample code snippet that demonstrates the usage of the fseek function in C. This program involves the creation of a simple text file, writing data to it, and utilizing fseek to retrieve and display data from a specified position within the file.

Example

#include <stdio.h>
int main() {
    FILE *file;
const char *filename = "example.txt";
    char buffer[100];
    // Open the file in write mode to create and write data
    file = fopen(filename, "w");
    if (file == NULL) {
perror("Error opening the file");
        return 1;
    }
    // Write some data into the file
fputs("Hello, this is a sample file.\n", file);
fputs("This is line 2.\n", file);
fputs("This is line 3.\n", file);
    // Close the file
fclose(file);
    // Open the file in read mode
    file = fopen(filename, "r");
    if (file == NULL) {
perror("Error opening the file");
        return 1;
    }
    // Move the file pointer to the start of the third line (skipping two lines)
fseek(file, 0, SEEK_SET); // Start from the beginning of the file
fgets(buffer, sizeof(buffer), file); // Read line 1
fgets(buffer, sizeof(buffer), file); // Read line 2
    // Now, the file pointer is at the start of line 3. Print it and subsequent lines.
    while (fgets(buffer, sizeof(buffer), file) != NULL) {
printf("%s", buffer);
    }
    // Close the file
fclose(file);
    return 0;
}

Output:

Output

This is line 3.

Explanation:

In this instance, the necessary header files stdio.h are included to facilitate standard input/output functions. We define the main function, which serves as the starting point for our program.

Three variables are declared:

A pointer to the file stream is stored in the FILE*file variable for interacting with the file.

The constant character pointer *filename contains the file name "example.txt" that we aim to generate and handle.

Charbuffer[100]: 100-character character array (buffer) , which will hold the information retrieved from the file.

  • The file is opened in write mode ("w") . The file will be generated if it doesn't already exist. We use the error function to output an error message and return an error code if the file opening fails.
  • Using the fputs function , three lines of data are written into the file. Each time fputs is called, a line of text is written to the file and separated by a newline (n) .
  • We use the fclose function to close the file after writing data into it.
  • After that, the file is reopened in read mode ("r") so that we can read data from it. We use the error function to print an error message and return an error code of (1) if the file opening fails.
  • The first two lines of the file are read using fgets , which is called twice after moving the file pointer to the beginning of the file using the fseek function . However, we effectively bypass these lines by not storing them in any variables.
  • The file pointer is currently at the beginning of the third line . Each line is read from the file using fgets and stored in the buffer array using a while loop . When there are no more lines in the file to read, the fgets function returns NULL , and the loop continues until it does.
  • After that, we use the printf function within the loop to print each line in the buffer array.
  • After reading and printing each line, we close the file using the fclose
  • The main function returns 0 to show that the program has been successfully run.
  • This program first creates a text file called "example.txt", and inserts three lines of data into it. After that, it reads and prints the file's content beginning on the third line. Using the fseek function, the program effectively skips the first two lines before reading and printing the following lines in a loop using fgets . Finally, it terminates the file and ends gracefully.
  • Complexity Analysis:

Time Complexity:

Utilizing the fputs function to add information to a file maintains a time complexity of O(1) for every invocation.

Given that fgets function reads characters until it encounters a newline character or fills the specified buffer size, the operation of reading information from the file within the loop results in a time complexity of O(n), where n represents the total count of characters present in the file.

The overall time complexity of the program can be approximated as O(n), where n represents the total character count within the input file.

Space Complexity:

The size of the buffer utilized to store each line extracted from the file plays a crucial role in determining the space complexity of the program. In this case, the buffer size has been established at 100 characters (char buffer[100]).

The memory requirements for additional program variables, such as the file pointer FILE file and the constant strings const char filename, remain fixed and do not vary with the input size.

Its spatial complexity is O(1) as the software employs a buffer of constant size to store the lines retrieved from the file. As the input size grows, the spatial complexity persists unchanged.

rewind:

The rewind function in C programming is employed to reset the file position indicator back to the start of a file. This function is part of the C Standard Library (stdio.h) and is commonly used to reset the file pointer, allowing you to re-read from the start of a file following data reading or writing operations.

The rewind function in C programming from the standard library is employed to reset the file position indicator back to the start of a file. This function is designed to work with file streams represented by FILE pointers and is declared in the header file stdio.h. By using rewind, you can reposition the file pointer to the beginning of the file following previous file operations, enabling you to access and modify data from the file's initial position again.

The rewind function in C works on a file stream (represented by a FILE pointer) and doesn't require any input parameters. It initiates the subsequent read or write operation from the start by resetting the file position indicator of the designated file stream.

Syntax:

Example

void rewind(FILE *stream);

Parameters:

A stream refers to a pointer pointing to a FILE object that represents the file stream requiring a reset of the file position indicator.

Return Value:

As the rewind function is of void type, it does not have a return value.

Usage:

The primary purpose of the rewind function is to allow you to re-read data from the start of a file once it has reached the end or completed previous file operations. This feature is particularly beneficial when you require multiple file processing iterations or wish to commence re-reading the content without reopening the file.

Remember that the rewind method is commonly used with binary or text files that have a consistent record length. Using rewind with text files that have varying line endings like n on Unix or Windows systems can lead to unforeseen outcomes. When dealing with text files, consider employing alternative strategies or using fseek with care.

Program:

Example

#include <stdio.h>
int main() {
    FILE *file = fopen("example.txt", "r");
    if (file == NULL) {
perror("Error opening the file");
        return 1;
    }
    // Read some data from the file
    char buffer[100];
fgets(buffer, sizeof(buffer), file);
printf("Read: %s", buffer);
    // Reset the file position indicator to the beginning of the file
    rewind(file);
    // Read from the beginning of the file again
fgets(buffer, sizeof(buffer), file);
printf("Read again: %s", buffer);
    // Close the file
fclose(file);
  return 0;
}

Output:

Output

Read: Hello, this is a sample file.
Read again: Hello, this is a sample file.

Explanation:

  • In this example, we include the header file that is required for typical input/output
  • Define the main function , which is where our program starts.
  • After that, create a file pointer variable to handle files. Use the fopen function to open the file in read mode ("r") .
  • In this step, we use the fopen function to try and open the file "example.txt " in read-only mode. If the attempt to open the file fails ( returns NULL ), it either doesn't exist or can't be opened. In this case, we use the error function to print an error message and return with an error code of (1).
  • Use the fgets function to read some data from the file.
  • A line of text is read from the file and stored in the buffer array using the fgets function . The fgets function reads characters from the file up to the capacity of the buffer (sizeof(buffer)) or until it encounters a new line. After that, a null terminator ('0') is = added to the end of the read string to convert it to a usable C string. Using the printf function, we output the contents of the buffer.
  • Use the rewind function to reset the file position indicator to the file's beginning.
  • In this phase, the file pointer file is passed as an argument to the rewind function . The file position indicator linked to the file stream is moved to the beginning of the file when it is reset by the rewind function . It enables us to access material earlier in the file again from the beginning.
  • Using the fgets function , read the file again from the beginning.
  • We may now call the fgets function again to read a line from the file's beginning after rewind and reset the file position indication. The newline is saved in the buffer array before being printed using the printf function .
  • Use the fclose function to close the file.
  • We use the fclose function to close the file to release system resources related to the file stream.
  • If the program is successful, the main function returns 0.
  • If the program opens a file, reads a line of text, uses the rewind function to move the file position indication back to the beginning, and then reads a line from the beginning of the file again. After that, it politely ends by closing the file. With the help of the rewind function , we may repeatedly read data from the file's beginning without reopening it.
  • Complexity Analysis:

Time Complexity:

Using the fopen function to access the file: The act of opening a file is commonly believed to exhibit an O(1) time complexity. This characteristic relies more on the efficiency of the operating system and the underlying file system in handling file-related tasks rather than being directly influenced by the file's size.

Reading a line of text from a file can be achieved using the fgets function. It's worth noting that fgets operates with an O(n) time complexity, where n represents the count of characters being read from the file. In the specific scenario outlined, fgets reads from the file up to the size specified by sizeof(buffer) (which in this case is set to a constant value of 100) and retrieves characters accordingly.

Resetting the file position indicator with the rewind function is an operation that executes in constant time, denoted as O(1). This function effectively relocates the file position indicator to the start of the file.

Reading an additional line of text from a file using fgets: As previously mentioned, the time complexity of fgets is O(n), with n representing the total number of characters read from the file. In this scenario, fgets reads up to the size of the buffer, which in this case is again a fixed value (100), from the file.

The overall time complexity of the given code can be estimated to be around O(n), where n represents the combined count of characters processed in the initial and subsequent fgets functions, or the overall number of characters extracted from the file.

Space Complexity:

The file object: Irrespective of the file's size or the quantity of characters processed, the file pointer FILE *file maintains a consistent space complexity, which is O(1).

The buffer array consists of a fixed-size character array char buffer[100] with a capacity of 100 characters. Due to the constant size of the buffer, it occupies space complexity of O(100) or O(1).

Considering that the provided code employs a buffer of a predetermined size and its memory consumption does not scale with the input file or data size, the space complexity of the code is O(1).

Comparison of fseek and rewind:

Both functions fseek and rewind in C are designed to manipulate the position of files, yet they have distinct functionalities. Unlike rewind, which straightforwardly resets the file pointer to the start of the file, fseek provides a more detailed control by allowing you to specify the exact position using offset and origin parameters. Your specific file processing requirements and the level of precision needed in managing the file pointer will dictate whether fseek or rewind is more suitable for your task. There are multiple scenarios where fseek diverges from rewind in terms of functionality.

Functionality:

The fseek function enables repositioning the file position indicator within a file to a specified location. This functionality permits moving the file pointer to any desired position by specifying the offset and origin parameters, which include SEEKSET, SEEKCUR, and SEEK_END options.

  • When used without additional parameters, the rewind method effectively repositions the file's indicator to the start. This action consistently relocates the file pointer to the file's initial position.
  • Function Signature:

  • The fseek function sets the file position indicator for the stream, using the specified offset and origin. It returns zero if successful.

Rewinding:

The rewind function rewinds the position indicator of the stream back to the beginning.

Arguments:

fseek:

  • stream: A reference to a FILE object representing the desired file stream .
  • Offset: The number of bytes the file pointer must move. Depending on the movement's direction, it might have either a positive or negative
  • Origin: It is the starting point from which to apply the offset. Any one of the following three values can be used for it:
  • SEEK_SET (0): The offset is measured from the file's start .
  • SEEK_CUR (1): The offset is about the file pointer's current location.
  • SEEK_END (2): Relative to the file's end, the offset.

reset_stream:

The rewind function takes a

  • stream parameter, which is a reference to a FILE object that represents the specific file stream requiring the reset of the file position indicator.
  • File pointer Movement:

The fseek function gives you the ability to specify the exact position where the file pointer should be located, allowing for precise navigation within the file.

reset:

  • Irrespective of the current position, this method consistently relocates the file pointer to the start of the file.
  • Use Cases:

fseek:

This function is beneficial for relocating the file pointer to designated positions within the file, like skipping over headers or pinpointing specific records in a binary file. It proves to be handy when there is a requirement to access specific file locations for reading from or writing to them.

reset:

  • This function is perfect for situations where you need to start fresh by reading or writing from the very beginning and resetting the file pointer to the start of the file.
  • It is a popular choice when you aim to begin reading data anew or when there is a requirement to redo the complete processing of the file.
  • Flexibility:

The fseek function offers enhanced flexibility by using the offset and origin parameters, allowing for varied file positioning requirements.

resetFilePointer:

  • By default, the resetFilePointer function provides a simple method to reposition the file pointer to the start of the file.
  • Handling errors:

The fseek function yields an integer value upon execution. If successful, the function will return 0; however, in case of an error, a non-zero value will be returned, typically signaling issues related to the file or its positioning. Subsequently, following the execution of the fseek function, one can employ the error function to inspect for any anomalies.

  • The function rewind returns an object without a value (void). It effectively resets the file position indicator to the start of the file without providing any feedback on errors.
  • Handling any potential errors that may arise during file opening or other operations must be done separately since rewind does not provide error codes.
  • Use of Binary files:

fseek:

  • When dealing with binary files, the fseek function proves to be quite beneficial.
  • It enables direct retrieval of records or data structures by allowing precise positioning within the binary file.

resetfilepointer:

  • Utilizing the rewind function is essential for handling binary files.
  • In situations where binary data needs to be processed from the start, resetting the file pointer to the beginning of the binary file is a necessary step.

Input Required

This code uses input(). Please provide values below: