fseek函数

fseek函数:

int fseek(FILE *_FILE, long _Offset, int _Origin);

函数设置文件指针stream的位置,如果执行成功,stream将指向以fromwhere为基准,偏移量offset(指针偏移量)个字节的位置,函数返回0。如果执行失败则不改变strea.m指向的位置,函数返回一个0。

#include<stdio.h>
#include<string.h>

struct student
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {0};
    FILE *p = fopen("./c.txt","rb");
    
    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fclose(p);
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C/20190725$ ./fseek

name = wang,age = 21

 

#include<stdio.h>
#include<string.h>

struct student
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {0};
    FILE *p = fopen("./c.txt","rb");
    
    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fseek(p,0-sizeof(struct student),SEEK_CUR);

    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fclose(p);
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C/20190725$ ./fseek

name = wang,age = 21

name = wang,age = 21

 

#include<stdio.h>
#include<string.h>

struct student
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {0};
    FILE *p = fopen("./c.txt","rb");
    
    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    //fseek(p,0-sizeof(struct student),SEEK_CUR);

    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fclose(p);
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C/20190725$ ./fseek

name = wang,age = 21

name = qing,age = 34

 

#include<stdio.h>
#include<string.h>

struct student
{
    char name[100];
    int age;
};

int main()
{
    struct student st = {0};
    FILE *p = fopen("./c.txt","rb");
    
    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    //fseek(p,0-sizeof(struct student),SEEK_CUR);
    fseek(p,0-sizeof(struct student),SEEK_END);

    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fseek(p,0-sizeof(struct student),SEEK_END);

    memset(&st,0,sizeof(struct student));
    fread(&st,sizeof(struct student),1,p);
    printf("name = %s,age = %d\n",st.name,st.age);

    fclose(p);
    return 0;
}

运行结果:

exbot@ubuntu:~/wangqinghe/C/20190725$ ./fseek

name = wang,age = 23

name = he,age = 557

name = he,age = 557

posted @ 2019-07-28 20:01  王清河  阅读(920)  评论(0编辑  收藏  举报