Javatpoint Logo
Javatpoint Logo

fseek() vs rewind() in C

In this article, we will discuss the difference between fseek() and rewind() functions in C. But before discussing the differences, we must know about the fseek() and rewind() functions in C.

fseek():

The fseek() function in the C programming language is used to relocate the file position indication to a predetermined location inside a file, commonly known as the file pointer. You can use it to alter where the next read or write operation will occur in the file. This function is a component of the C Standard Library, which is frequently used in conjunction with file streams (FILE pointers) to carry out file operations.

The C Standard Library's fseek() function's functionality may vary significantly between systems or implementations. However, the function's overall goal and behavior adhere to the C standard.

The fseek() function adjusts the file position indication for the provided file stream to a specified position. Each file stream has a concept known as a file position indication that designates where the following read or write operation will occur in the file.

Syntax:

The fseek() syntax is as follows:

Parameters:

Stream: A reference to a FILE object representing the desired file stream.

Offset: It represents the number of the bytes that the file pointer must move. Depending on the movement's direction, it might have either a positive or negative value.

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): It is relative to the file's end.

Return value:

If the operation is successful, it returns 0 values. If an error occurs, it returns a value other than zero.

The fseek() method returns an integer result to indicate whether the operation was successful or unsuccessful. If the operation is successful, it returns 0; otherwise, a non-zero value is returned. If an issue occurs, you can learn more about the individual error using the errno variable or the error () function.

It's vital to remember that only binary files have fseek()'s behavior behaving as expected. Due to variations in line-ending protocols between operating systems, using the fseek() fucntion on text files with variable-length line endings may produce surprising results. Using methods like fgetc() or fgets() method to read from a specific line in text files is typically advised.

Program:

Here is an example program that uses C's fseek() function. In this program, a straightforward text file will be created, some data will be written into it, and then fseek() will be used to read and output data from a given location in the file.

Output:

This is line 3.

Explanation:

In this example, the required header files stdio.h are included for use with normal input/output operations. We specify the main() function, which is where our program begins.

Three variables are declared:

FILE *file: A pointer to the file stream that will be utilized to interact with the file is contained in the FILE*file variable.

Const char *filename: The file name that we wish to create and manipulate is included in the constant text "example.txt" in the char *filename variable.

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:

Using the fputs() function to write data to a file requires O(1) time complexity for each call.

Since fgets() reads characters until it hits a newline or reaches the set buffer size, reading data from the file inside the loop takes O(n) time complexity, where n is the number of characters in the file.

The program's overall time complexity can be estimated as O(n), where n is the total number of characters in the input file.

Space Complexity:

The buffer size used to hold each line read from the file significantly determines the program's space complexity. In this instance, the buffer size is set to 100 characters (char buffer[100]).

The memory needs of other program variables, like the file pointer FILE *file and the constant strings const char *filename, are constant and independent of the input size.

Its space complexity is O(1) because the program utilizes a fixed-size buffer to hold the lines read from the file. With increasing input size, the space complexity remains the same.

rewind():

The rewind() standard library function in C programming is used to reset the file position indicator to the beginning of a file. It is a component of the C Standard Library (stdio. h), and its most typical usage is to reset the file pointer so that you can read from the beginning of a file once more after reading or writing data.

The standard library method rewind() in C programming is used to reset the file position indicator to the beginning of a file. It is intended to deal with file streams (FILE pointers) and is specified in the header file stdio.h. The rewind() function enables you to move the file pointer back to the file's beginning after executing prior file operations, allowing you to read or write data from the file's beginning once more.

The C language's rewind() function operates on a file stream (represented by a FILE reference) without accepting any input arguments. It starts the next read or write operation from the beginning by resetting the file position indicator of the specified file stream.

Syntax:

Parameters:

Stream: A pointer to a FILE object representing the file stream for which the file position indication must be reset.

Return Value:

Since the rewind() function is a void function, it has no value to return.

Usage:

The rewind()'s main function enables you to read data from the file's beginning once more after reaching the end or finishing prior file operations. It is especially helpful if you need to process the file more than once or want to start reading the material over without revisiting the file.

Remember that the rewind() function typically works with binary or text files with fixed-length record structures. The rewind() function may provide unexpected results if you work with text files with variable-length line endings, such as n, on Unix-like platforms or Windows. When processing text files, you can use other techniques or fseek() cautiously.

Program:

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 fopen() to open the file: Opening a file is typically thought to have an O(1) time complexity. It depends on the operating system's and underlying file system's effectiveness in managing file operations rather than the file's size directly.

Using fgets() to read a line of text from the file: Fgets() has an O(n) time complexity, where n is the number of characters read from the file. In this instance, it reads up to the sizeof(buffer), a fixed value in the provided code (100), and characters from the file.

Using rewind() to clear the file position indicator: With constant time, or O(1), the rewind() function moves the file position indicator to the beginning of the file.

Using fgets() to read a further line of content from the file: As was already established, the time required by fgets() is O(n), where n is the total amount of characters read from the file. In this instance, it reads up to sizeof(buffer), which is once again a constant value (100) from the file.

The total time complexity of the provided code can be roughly calculated as O(n), where n is the sum of the characters read in the first and second fgets() calls or the total amount of characters read from the file.

Space Complexity:

The file variable: Regardless of the file size or the number of characters read, the file pointer FILE *file uses constant space, i.e., O(1).

The buffer array: The character array char buffer[100] in the buffer array has a fixed size of 100 characters. Since the buffer size is constant, it takes up O(100) or O(1) space complexity.

Since the offered code utilizes a fixed-size buffer and its memory usage is independent of the size of the input file or input data, its overall space complexity is O(1).

Comparison of fseek() and rewind():

fseek() vs rewind() in C

Both C's fseek() and rewind() functions are used to position files but serve different purposes. Rewind() is easier since it always resets the file pointer to the beginning. However, fseek() offers more precise control over the file pointer's position with offset and origin arguments. Your particular needs for file processing and the degree of control you require over the file pointer's position will determine which of the two routines you should use. There are various functions where fseek() function differs from the rewind() function.

Functionality:

fseek():

  • The file position indicator can be set to a specific location within a file using the fseek() function. It allows shifting the file pointer to any location using the offset and origin options (SEEK_SET, SEEK_CUR, and SEEK_END).

rewind():

  • Without any other options, the rewind() function directly resets the file position indicator to the beginning of the file. The file pointer is always moved to the beginning of the file.

Function Signature:

fseek():

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

rewind():

  • void rewind(FILE *stream);

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.

rewind():

  • stream: A pointer to a FILE object representing the file stream for which the file position indication must be reset.

File pointer Movement:

fseek():

  • It provides control over where the file pointer should be placed and enables more accurate movement of the file pointer inside the file.

rewind():

  • Regardless of the current location, this function always moves the file pointer to the beginning of the file.

Use Cases:

fseek():

  • It is helpful for moving the file pointer to specified locations within the file, such as bypassing headers or locating certain records in a binary file.
  • It is suitable for situations when you need to read from or write to particular file locations.

rewind():

  • It is ideal for when you wish to read or write from scratch and reset the file pointer to the file's beginning.
  • It is commonly used when you want to start reading data again from the beginning or when you need to reprocess the entire file.

Flexibility:

fseek():

  • The offset and origin variables in fseek() provide it more flexibility, making it appropriate for different file placement needs.

rewind():

  • Without any further options, the rewind() function offers a straightforward way to reset the file reference to the beginning of the file.

Handling errors:

fseek():

  • An integer value is returned by the fseek() function. The function returns 0 if it is successful. It returns a non-zero number in the event of an error, often indicating a problem with the file or its placement.
  • After calling the fseek() function, you can use the error() function to look for faults.

rewind():

  • Rewind() function returns a valueless object (void). Without giving any incorrect feedback, it automatically resets the file position indicator to the beginning of the file.
  • You must deal with potential errors (if any) encountered during file opening or other file operations individually because rewind() does not return any error codes.

Use of Binary files:

fseek():

  1. When working with binary files, fseek() is especially helpful.
  2. Direct access to records or data structures is possible since you can navigate to specific locations in the binary file.

rewind():

  1. Binary files can also be used using the rewind() function.
  2. When processing binary data from scratch, resetting the file reference to the beginning of the binary file is crucial.






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