1.fseek
用于设置文件中位置指针的偏移量。       
1)头文件
#include <stdio.h>       
2)函数原型
int fseek(FILE *stream, long offset, int whence);       
3)参数
stream:要操作的文件指针。
offset:表示以whence为起始点的偏移字节数。
whence:表示offset的起始点位置,可以是以下之一:
SEEK_SET:文件的开头。
SEEK_CUR:当前读写位置。
SEEK_END:文件的末尾。
4)返回值
返回0,表示设置成功;若返回非零值,表示出错。
5)示例:(打开ftest文件,将位置指针移动到文件末尾)
#include <stdio.h>
int main()
{
        FILE *fp = fopen("ftest", "r");
        if (!fp) {
                printf("error: ftest open\n");
                return -1;
        }
        if (fseek(fp, 0, SEEK_END)) {
                printf("error: ftest fseek\n");
                fclose(fp);
                return -1;
        }
        printf("succeed: ftest fseek\n");
        fclose(fp);
        return 0;
}
6)编译运行并查看测试结果
succeed: ftest fseek
2.ftell
用于获取文件中位置指针的偏移量。       
1)头文件
#include <stdio.h>       
2)函数原型
long ftell(FILE*stream);       
3)参数
stream:要操作的文件指针。
4)返回值
返回当前文件位置偏移量;若返回-1,表示出错。
5)示例:(打开ftest文件,将位置指针移动到文件末尾,查看当前的文件长度)
#include <stdio.h>
int main()
{
        int ft;
        FILE *fp = fopen("ftest", "r");
        if (!fp) {
                printf("error: ftest open\n");
                return -1;
        }


        ft = ftell(fp);          //查看当前的文件偏移量
        if (ft == -1) {
                printf("error: ftest ftell1\n");
                fclose(fp);
        }
        printf("ftest ftell1: %d\n", ft);


        if (fseek(fp, 0, SEEK_END)) {       //将位置指针移动到文件末尾
                printf("error: ftest fseek\n");
                fclose(fp);
        }


        ft = ftell(fp);           //查看当前的文件偏移量
        if (ft == -1) {
                printf("error: ftest ftell2\n");
                fclose(fp);
        }
        printf("ftest ftell2: %d\n", ft);
        fclose(fp);
        return 0;
}
6)编译运行并查看测试结果
ftest ftell1: 0
ftest ftell2: 15
3.rewind
用于将文件中位置指针设置到文件开头。
1)头文件
#include <stdio.h>
2)函数原型
void rewind(FILE*stream);
3)参数
stream:要操作的文件指针。
4)返回值
无。
5)示例:(打开ftest文件,将位置指针移动到文件末尾,再使用rewind)
#include <stdio.h>
int main()
{
        int ft;
        FILE *fp = fopen("ftest", "r");
        if (!fp) {
                printf("error: ftest open\n");
                return -1;
        }


        if (fseek(fp, 0, SEEK_END)) {  //将位置指针移动到末尾
                printf("error: ftest fseek\n");
                fclose(fp);
        }


        ft = ftell(fp);               //查看当前的文件偏移量
        if (ft == -1) {
                printf("error: ftest ftell\n");
                fclose(fp);
        }
        printf("ftest ftell1: %d\n", ft);


        rewind(fp);                //将位置指针移动到开头


        ft = ftell(fp);               //查看当前的文件偏移量
        if (ft == -1) {
                printf("error: ftest ftell\n");
                fclose(fp);
        }
        printf("ftest ftell2: %d\n", ft);
        fclose(fp);
        return 0;
}
6)编译运行并查看测试结果
ftest ftell1: 15
ftest ftell2: 0

    您需要登录后才可以回帖 登录 | 立即注册

    本版积分规则

    Powered by Discuz! X3.5  © 2001-2013 Comsenz Inc.