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 ;
}
相关推荐
CS semi1 分钟前
Rust从入门到实战
开发语言·后端·rust
HR Zhou6 分钟前
群体智能优化算法-䲟鱼优化算法 (Remora Optimization Algorithm, ROA,含Matlab源代码)
开发语言·算法·matlab·优化·智能优化算法·群体智能优化
敖云岚1 小时前
【云原生技术】容器技术的发展史
开发语言·云原生·perl
忧郁的蛋~1 小时前
JavaScript性能优化的12种方式
开发语言·javascript·性能优化
人工智能研究所1 小时前
使用OpenCV与Python编写自己的俄罗斯方块小游戏
开发语言·python·opencv
DDD小小小宇宙1 小时前
python列表基础知识
开发语言·windows·python
海盗强1 小时前
prototype和proto的区别
开发语言·javascript·原型模式
哥谭居民00011 小时前
mybatis注册一个自定义拦截器,拦截器用于自动填充字段
java·开发语言·jvm·mybatis
钟离墨笺2 小时前
【c++】【智能指针】什么情况下不适合智能指针
开发语言·c++
moz与京2 小时前
【记】如何理解kotlin中的委托属性?
android·开发语言·kotlin