C 主要函数解析

1、fseek 函数

int fseek(FILE *stream, long offset, int fromwhere);

第一个参数stream为文件指针

第二个参数offset为偏移量正数表示正向偏移,负数表示负向偏移

第三个参数origin设定从文件的哪里开始偏移,可能取值为:SEEK_CUR、 SEEK_END 或 SEEK_SET

SEEK_SET: 文件开头

SEEK_CUR: 当前位置

SEEK_END: 文件结尾

简言之:

fseek(fp,100L,0);把stream指针移动到离文件开头100字节处;

fseek(fp,100L,1);把stream指针移动到离文件当前位置100字节处;

fseek(fp,-100L,2);把stream指针退回到离文件结尾100字节处。

2、ftell函数

long ftell() 函数

作用是 获取文件的 当前指针位置 相对于 文件首地址 的 偏移字节数

示例(根据以上函数读取文件内容):

复制代码
static char* get_file_msg(char* file)
{
	FILE *fh = NULL;
	char *ptr = NULL;
	long flen = 0;
	int ret = 0;

	fh = fopen(file, "r");
	if(NULL == fh)
	{
		printf(" fopen err \n")
		goto end;
	}


	ret = fseek(fh, 0, SEEK_END)
	if(ret != 0)
	{
		printf(" fseek SEEK_END fail \n");
		goto end;
	}

 	flen = ftell(fh);
	if(flen < 0)
	{
		printf(" ftell failed [%d] ", errno);
		goto end;
	}

	ret = fseek(fh, 0, SEEK_SET);
	if(0 != ret)
	{
		printf("fseek SEEK_SET failed" );
		goto end;
	}

	ptr = (char*)malloc(flen + 1);
	memset(ptr, 0x00, flen+1);
	ret = fread(ptr, sizeof(char), flen, ret);
	if(flen != ret)
	{
		printf(" fread failed");
		free(ptr);
		ptr = NULL;
	}

end:
	if(NULL != fh)
	{
		fclose(fh);
	}

	return ;
}
相关推荐
caimouse5 分钟前
ReactOS 窗口系统分析(14):计时器/属性/加速键/热键 — timer.c + prop.c + accelerator.c + hotkey.c
c语言·开发语言·reactos
circuitsosk12 分钟前
Python 模块与包管理:import 机制、虚拟环境与 pip 完全指南
开发语言·python·pip·依赖管理·模块与包
就叫飞六吧12 分钟前
两道门:X-Frame-Options 和 SameSite 到底谁管什么
开发语言·chrome·ai编程
水饺编程13 分钟前
第5章,[Win32 章节] :贝塞尔样条曲线(一)
c语言·c++·windows·visual studio
fl17683127 分钟前
基于C#WPF实现的内存加速球清理类似360加速球内存清理
开发语言·c#·wpf
weixin_4407305031 分钟前
python+request实现接口-小结
开发语言·python
ZJU_统一阿萨姆1 小时前
【算子开发】扫描(Scan)与前缀和
开发语言·arm开发·架构·系统架构·硬件架构
-凌凌漆-1 小时前
【C语言】结构体typedef struct与struct的区别
c语言·开发语言
caimouse1 小时前
ReactOS 窗口系统分析(24):输入法 — ime.c
c语言·reactos
for_ever_love__1 小时前
PySpark学习: 数据输出
开发语言·python·学习·spark