文件的随机读写:fseek/ftell/rewind

1.fseek


    //        int fseek(FILE* stream, long int offset, int origin);//根据文件指针的位置(int origin)和偏移量来定位文件指针
    //            FILE* stream:指向待操作文件的文件指针
    //            long int offset:设置偏移量
    //            int origin:以什么位置为参考进行偏移。只能是这三个位置中的任意一个:SEEK_SET(文件起始位置)\SEEK_CUR(文件当前位置)\SEEK_END(文件末尾位置)

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//使用文件
		//读文件
		//当前"test.dat"文件内存放的内容是:abcdefghi
	int i = 0;
	int ch = 0;
	for (i = 0; i < 5; i++)
	{
		ch = fgetc(pf);
		printf("%c", ch);	//读取五次打印出来的内容是:abcde
	}
	fseek(pf, -3, SEEK_CUR);	//读取文件结束后文件指针自动向后走一步,现在指向字母f,SEEK_CUR表示文件指针的当前位置,向后(左)偏移3,应该定为到字母c
	ch = fgetc(pf);
	printf("%c", ch);	//c 

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

2.ftell


    //        long int ftell(FILE* stream);//函数用来返回文件指针当前位置相对于起始位置的偏移量,可以清楚的知道文件指针走了多远
    //            FILE* stream:指向待操作文件的文件指针
    //            long int ftell(返回值):返回文件指针当前位置相对于起始位置的偏移量

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//使用文件
		//读文件
		//当前"test.dat"文件内存放的内容是:abcdefghi
	int i = 0;
	int ch = 0;
	for (i = 0; i < 5; i++)
	{
		ch = fgetc(pf);
		printf("%c", ch);	//读取五次打印出来的内容是:abcde
	}
	printf("%d\n", ftell(pf));//5  
		//读取了从偏移量为0到偏移量为4的5个字母之后,文件指针会自动向后偏移1偏移量到5偏移量处,所以当前位置(5偏移量处)相对起始位置(0偏移量处)的偏移量为5

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

3.rewind


    //        void rewind(FILE* stream);//函数的作用是让文件指针的位置回到文件的起始位置(即0偏移量处)
    //            FILE* stream:指向待操作文件的文件指针
    //            void rewind:没有返回值

#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
int main()
{
	//打开文件
	FILE* pf = fopen("test.dat", "r");
	if (pf == NULL)
	{
		perror("fopen");
		return 1;
	}

	//使用文件
		//读文件
		//当前"test.dat"文件内存放的内容是:abcdefghi
	int i = 0;
	int ch = 0;
	for (i = 0; i < 5; i++)
	{
		ch = fgetc(pf);
		printf("%c", ch);	//读取五次打印出来的内容是:abcde
	}
	printf("%d\n", ftell(pf));//5  
	rewind(pf);		//让文件指针回到文件的起始位置,如果再次读文件就会重新从第一个元素开始
	ch = fgetc(pf);
	printf("%c", ch);	//a

	//关闭文件
	fclose(pf);
	pf = NULL;
	return 0;
}

猜你喜欢

转载自blog.csdn.net/libj2023/article/details/131746092