SoFunction
Updated on 2025-04-27

Summary of the usage of fseek function in C language

fseekFunctions are one of the core functions used for file operations in the C language standard library, mainly used to implement random access to files. By flexibly controlling the position of file pointers, it breaks through the limitation of sequential read and write, allowing developers to read and write operations anywhere in the file. The following is from multiple dimensionsfseekThe function is fully parsed.

1. Function Overview

fseekThe function is defined as follows:

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

Function: Reposition the location of the file pointer so that it points tooriginAs the benchmark, offsetoffsetThe position of bytes.
Return value: successfully returned0, failed to return a non-zero value (usually-1)。
Header file:<>

2. Detailed explanation of parameters

*stream

A pointer to an open file, obtained through fopen or similar functions. Make sure that the file is opened in a mode that supports positioning (such as "rb+", "wb+", etc.).

2.long offset

Offset, unit in bytes:

  • Positive value: Move the pointer toward the end of the file.
  • Negative value: Move the pointer toward the beginning of the file.
  • Example:offset=100LIndicates moving backwards by 100 bytes.offset=-50LIndicates moving forward by 50 bytes.

3.int origin

For reference position, the following macro definition values ​​can be selected:

Macro constants Value describe
SEEK_SET 0 Start of the file
SEEK_CUR 1 Current location
SEEK_END 2 At the end of the file

3. Core application scenarios

1. Randomly read and write file contentsfseekAllows you to jump to a specified location in the file for reading and writing, suitable for scenarios where specific data blocks need to be modified. For example, modify a structure record in a binary file:

typedef struct {  
    long sno;  
    char name[10]();  
    float score[3]();  
} Student;  

void updateStudent(FILE *fp, Student *s, int pos) {  
    fseek(fp, pos * sizeof(Student), SEEK_SET); // Position the pos record    fwrite(s, sizeof(Student), 1, fp);          // Overwrite new data}  
``` ```  
*Cited Example Source:[7]()*  

2. Calculate file size combinationftellFunctions can quickly get file length:

long fileSize(FILE *fp) {  
    fseek(fp, 0, SEEK_END); //Locate to the end of the file    long size = ftell(fp);  // Get the current offset (i.e. the total number of bytes of the file)    fseek(fp, 0, SEEK_SET); // Restore pointer to the beginning of the file    return size;  
}  
``` ```  
*Cited Example Source:[1]()[2]()*  

3. Adjust the pointer in append mode if the file is used in append mode ("a+") opens, the write operation is always performed at the end of the file, butfseekAdjustable reading position:

FILE *fp = fopen("", "a+"); fseek(fp, -100L, SEEK_END); // Position to the end of the file100Read at bytes ``` ``` 

4. Precautions and common issues

1. Differences between text files and binary files

  • Text file: Some systems (such as Windows) will add newlines\nStore as\r\n,lead tofseekThe offset calculation may be inaccurate. It is recommended to use binary mode first ("rb"/"wb") Process structured data.
  • Binary file: The offset is calculated accurately and is suitable for passingfseekPosition to a specific location of a structure or array.

2. The impact of file opening mode

  • Read and write mode ("r+"/"w+"): Supports read and write operations at any location.
  • Added mode ("a+"): The write operation is always at the end of the file, but can be passedfseekAdjust the read position.

3. Problem of offset cross-border

likeoffsetExceed the actual range of the file (if set toSEEK_ENDAfter offset exceeds file length), it may result in undefined behavior or error. Need to be combinedftellCheck the current location.

4. Cross-platform compatibility

Different operating systems may handle pointers at the end of the file differently. It is recommended thatSEEK_ENDUse negative offsets to ensure portability.

5. Comparison with other file location functions

function

  • Function: Reset the file pointer to the beginning, equivalent tofseek(fp, 0, SEEK_SET)
  • difference:rewindNo return status, butfseekYou can judge whether it is successful by the return value.

function

  • Function: Returns the position of the current file pointer (relative to the number of bytes at the beginning of the file).
  • Combination use:fseekandftellCombined, complex positioning logic can be implemented, such as dynamically calculating offsets.

6. Error handling and debugging

1. Check the return value

if (fseek(fp, offset, origin) != 0) {  
    perror("fseek failed");  
    exit(EXIT_FAILURE);  
}  
``` ```  

2. Common causes of errors

  • The file is not opened in a mode that supports positioning.
  • The offset exceeds the actual range of the file.
  • Try writing to read-only files.

7. Advanced application examples

Scenario: Modify the k data in a file containing N student records.

FILE *fp = fopen("",  "rb+");  
if (fp == NULL) {  
    perror("File open error");  
    return;  
}  

Student stu;  
int k = 3; // Modify the third recordfseek(fp, (k-1) * sizeof(Student), SEEK_SET);  
fread(&amp;stu, sizeof(Student), 1, fp);  

[0]()   = 95.0; // Modify the scorefseek(fp, (k-1) * sizeof(Student), SEEK_SET);  
fwrite(&amp;stu, sizeof(Student), 1, fp);  

fclose(fp);  

8. Summary

fseekFunctions are the core tool for implementing random access in C file operations. Its flexibility and efficiency make it widely used in scenarios such as binary file processing, log analysis, and database indexing. Developers need to pay attention to the details related to file mode and offset calculation, and combine it withftelland error handling mechanisms improve the robustness of the code. By reasonable usefseek, can significantly optimize file read and write efficiency and meet complex data processing needs.

This is the end of this article about the usage of fseek functions in C. For more related content of fseek functions in C, please search for my previous articles or continue browsing the related articles below. I hope everyone will support me in the future!