The 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:
<code class="c">int fseek(FILE *stream, long int offset, int whence);</code>
Among them:
stream
: Pointer to the file stream to be operated on. offset
: The offset relative to the file starting from the position specified by whence
. whence
: Specify the position relative to offset
, 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:
<code class="c">fseek(stream, 0, SEEK_SET);</code>
Locate to a specific location in the file:
<code class="c">fseek(stream, 100, SEEK_SET); // 定位到文件中的第 101 个字节</code>
Move forward from the current position:
<code class="c">fseek(stream, 50, SEEK_CUR); // 从当前位置向前移动 50 个字节</code>
Move backward from the end of the file:
<code class="c">fseek(stream, -10, SEEK_END); // 从文件末尾向后移动 10 个字节</code>
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:
<code class="c">#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; }</code>
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!