当前位置: 首页>>代码示例>>用法及示例精选>>正文


C语言 fseek()用法及代码示例

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() 函数中有三个宏:

  1. SEEK_SET:从文件开头查找
  2. SEEK_CUR:从当前位置搜索
  3. 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;
}

输出

fseek example in c




相关用法

注:本文由纯净天空筛选整理自Souvik Saha大神的英文原创作品 fseek() function in C language with Example。非经特殊声明,原始代码版权归原作者所有,本译文的传播和使用请遵循“署名-相同方式共享 4.0 国际 (CC BY-SA 4.0)”协议。