How to use fseek function in C language
May 08, 2024 pm 12:54 PMThe fseek function is used to set the file pointer position in the file stream. Its syntax is fseek(FILE *stream, long int offset, int whence). Depending on the whence parameter, offset is relative to the beginning of the file (SEEK_SET), the current position (SEEK_CUR), or the end of the file (SEEK_END). If the operation is successful, 0 is returned; otherwise, -1 is returned and the errno variable is set to indicate the error.
Usage of fseek function in C language
The fseek function is used to set file reading and writing in the file stream The position of the pointer. The syntax is:
int fseek(FILE *stream, long int offset, int whence);
Among them:
stream
: Pointer to the file stream to be operated on.offset
: The offset relative to the file starting from the position specified bywhence
.whence
: Specify the position relative tooffset
, there are the following options:SEEK_SET
: Start from the beginning of the file.SEEK_CUR
: Start from the current file position.SEEK_END
: Start from the end of the file.
Usage:
Locate to the beginning of the file:
fseek(stream, 0, SEEK_SET);
Copy after loginLocate to a specific location in the file:
fseek(stream, 100, SEEK_SET); // 定位到文件中的第 101 个字节
Copy after loginMove forward from the current position:
fseek(stream, 50, SEEK_CUR); // 从当前位置向前移动 50 个字节
Copy after loginMove backward from the end of the file:
fseek(stream, -10, SEEK_END); // 从文件末尾向后移动 10 个字节
Copy after login
Return value:
If the operation is successful, the fseek function returns 0. If the operation fails, -1 is returned and the errno
variable is set to indicate the error.
Example:
The following example demonstrates how to navigate to a specific location in a file and read data:
#include <stdio.h> int main() { FILE *fp; char buffer[100]; // 打开文件 fp = fopen("test.txt", "r"); // 定位到文件中的第 101 个字节 fseek(fp, 100, SEEK_SET); // 从该位置读取数据 fread(buffer, 1, 50, fp); // 关闭文件 fclose(fp); return 0; }
The above is the detailed content of How to use fseek function in C language. For more information, please follow other related articles on the PHP Chinese website!

Hot Article

Hot tools Tags

Hot Article

Hot Article Tags

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

Usage of typedef struct in c language

The difference between strcpy and strcat in c language

How to implement the power function in C language

What to do if there is an error in scanf in C language
