C 中的 fseek() 函數
原型:
int feek(FILE *stream, long int offset, int origin);
參數:
FILE *stream, long int offset, int origin
返回類型:整型
函數的使用:
fseek()函數用於根據offset的值和文件的起始點,設置文件指示指針指向與文件流相關聯。函數 fseek() 的原型為:
int feek(FILE *stream, long int offset, int origin);
在這裏,offset
是從字節數origin
。
fseek() 函數中有三個宏:
- SEEK_SET:從文件開頭查找
- SEEK_CUR:從當前位置搜索
- SEEK_END:從文件尾查找
C 中的 fseek() 示例
#include <stdio.h>
#include <stdlib.h>
int main()
{
//Initialize the file pointer
FILE* f;
//Take a array of characters
char ch[100];
//Create the file for write operation
f = fopen("includehelp.txt", "w");
printf("Enter five strings\n");
for (int i = 0; i < 4; i++) {
//take the strings from the users
scanf("%[^\n]", &ch);
//write back to the file
fputs(ch, f);
//every time take a new line for the new entry string
//except for last entry.Otherwise print the last line twice
fputs("\n", f);
//clear the stdin stream buffer
fflush(stdin);
}
//take the strings from the users
scanf("%[^\n]", &ch);
fputs(ch, f);
//close the file after write operation is over
fclose(f);
//open a file
f = fopen("includehelp.txt", "r");
printf("\n...............print the strings..............\n");
while (!feof(f)) {
//takes the first 100 character in the character array
fgets(ch, 100, f);
//and print the strings
printf("%s", ch);
}
rewind(f);
printf("\n...............print the position before print a strings S..............\n");
fseek(f, 0, SEEK_SET);
printf("the file indicator position is - %d\n", ftell(f));
printf("\n...............print the position after print a strings ..............\n");
fgets(ch, 100, f);
printf("%s", ch);
fseek(f, 0, SEEK_CUR);
//print the current location
printf("the file indicator position is - %d\n", ftell(f));
printf("\n...............print the position after print all the strings ..............\n");
fseek(f, 0, SEEK_END);
printf("the file indicator position is - %d\n", ftell(f));
//close the file
fclose(f);
return 0;
}
輸出
相關用法
- C語言 fseek() vs rewind()用法及代碼示例
- C語言 fsetpos()用法及代碼示例
- C語言 fscanf()用法及代碼示例
- C語言 fread()用法及代碼示例
- C語言 feof()用法及代碼示例
- C語言 fillellipse()用法及代碼示例
- C語言 fgets()用法及代碼示例
- C語言 freopen()用法及代碼示例
- C語言 frexp()用法及代碼示例
- C語言 fclose()用法及代碼示例
- C語言 fflush()用法及代碼示例
- C語言 fgetc()用法及代碼示例
- C語言 fputc()用法及代碼示例
- C語言 fputs()用法及代碼示例
- C語言 fillpoly()用法及代碼示例
- C語言 ftell()用法及代碼示例
- C語言 fgets() and gets()用法及代碼示例
- C語言 ferror()用法及代碼示例
- C語言 fgetc() and fputc()用法及代碼示例
- C語言 fwrite()用法及代碼示例
注:本文由純淨天空篩選整理自Souvik Saha大神的英文原創作品 fseek() function in C language with Example。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。