描述
C库函数 int fseek(FILE *stream, long int offset, int whence) 根据给定的偏移量设置流的文件位置。
声明
int fseek(FILE *stream, long int offset, int whence)
参数
-
stream − 指向FILE对象的指针,用来标识数据流。
-
offset − 从whence处开始(偏移)的字节数。
-
whence − 开始偏移的位置, 必须是下面常量之一:
常量 | 描述 |
---|---|
SEEK_SET | 文件开头 |
SEEK_CUR | 文件指针的当前位置 |
SEEK_END | 文件结尾 |
返回值
成功返回零,失败返回非零值。
示例
#include <stdio.h> int main () { FILE *fp; fp = fopen("file.txt","w+"); fputs("This is http://www.tanlooger.com", fp); fseek( fp, 7, SEEK_SET ); fputs(" C Programming Language", fp); fclose(fp); return(0); }
对上面程序编译并运行,会创建一个file.txt文件并被写入了下面的内容。开始创建文件时写入的是“This is tutorialspoint.com”,但后来我们用fputs()语句将第7个字节之后的内容重写了,因而也就将如下内容写入了文件:
This is C Programming Language
下来我们用下面的程序来将上面程序创建的文件内容输出:
#include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break; } printf("%c", c); } fclose(fp); return(0); }
对上面程序编译并运行会得到如下结果:
This is the C Programming Language