fseek
Functions 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 dimensionsfseek
The function is fully parsed.
1. Function Overview
fseek
The 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 toorigin
As the benchmark, offsetoffset
The 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=100L
Indicates moving backwards by 100 bytes.offset=-50L
Indicates 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 contentsfseek
Allows 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 combinationftell
Functions 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, butfseek
Adjustable 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
\n
Store as\r\n
,lead tofseek
The 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 passing
fseek
Position 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 passedfseek
Adjust the read position.
3. Problem of offset cross-border
likeoffset
Exceed the actual range of the file (if set toSEEK_END
After offset exceeds file length), it may result in undefined behavior or error. Need to be combinedftell
Check the current location.
4. Cross-platform compatibility
Different operating systems may handle pointers at the end of the file differently. It is recommended thatSEEK_END
Use negative offsets to ensure portability.
5. Comparison with other file location functions
function
- Function: Reset the file pointer to the beginning, equivalent to
fseek(fp, 0, SEEK_SET)
。 - difference:
rewind
No return status, butfseek
You 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:
fseek
andftell
Combined, 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(&stu, sizeof(Student), 1, fp); [0]() = 95.0; // Modify the scorefseek(fp, (k-1) * sizeof(Student), SEEK_SET); fwrite(&stu, sizeof(Student), 1, fp); fclose(fp);
8. Summary
fseek
Functions 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 withftell
and 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!