⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 fseek_ftell.cpp

📁 本程序介绍了如何用C语言快速读写磁盘文件。
💻 CPP
字号:
#include <stdlib.h>
#include <stdio.h>
#include <string.h>
#include "Data_Struct.h"

/**************************************************************************
	fseek(文件指针,位移量(字节数),起始点)
	eg: fseek(fp,100L,SEEK_SET) // SEEK_SET==0,文件头
	    fseek(fp,50L,SEEK_CUR)  // SEEK_CUR==1,文件当前位置
		fseek(fp,-10L,SEEK_END) // SEEK_END==2,文件尾
***************************************************************************/
void fseek_ftell()
{
	test_struct list_tmp[MAX_NUM_test_struct] = {0};
	test_struct list[MAX_NUM_test_struct]	=
	{ 
		{"litong",'m',30},{"wangma",'f',21},{"hongja",'m',18},
		{"xiaomi",'f',30},{"zhaxue",'m',21},{"wuping",'f',18}
	};
	FILE *fp;
	int i;
	int pointer_position;

	if((fp = fopen( "E:\\C++_sample\\File_operating\\File_testing.txt", "w+" ))== NULL)	
	{
		printf("cannot open the file\n");
		exit(0);
	}
	for( i = 0; i < MAX_NUM_test_struct; i++ )  // finish writing data to file
		if( fwrite(&list[i],sizeof(test_struct),1,fp) != 1 )
		{
			printf("file write error!\n");
			exit(0);
		}

	for( i = 0; i < MAX_NUM_test_struct; i += 2 )  
	{
		fseek( fp, i * sizeof(test_struct), SEEK_SET ); // set the location of pointer 
		if( fread(&list_tmp[i],sizeof(test_struct),1,fp) != 1 )
			printf("file read error!\n");
		else
			printf("%s\t\t%c\t\t%d\n",list_tmp[i].name,list_tmp[i].sex,list_tmp[i].age);
	}
	i -= 2;

	pointer_position = ftell(fp);
	printf("\nThere is %d bytes before the location of fp pointer.\n",pointer_position);
	pointer_position = sizeof(test_struct) * (i += 1);
	printf("\nIt is right that there is %d bytes before the location of fp pointer.\n\n",pointer_position);
	fclose(fp);

	return;
}

⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -