学习笔记(74):C语言入门到精通-文件操作函数-下

立即学习:https://edu.csdn.net/course/play/10534/380029?utm_source=blogtoedu

学习目标
ftell(),fseek()
fgetpos(),fsetpos()

获取一个文件的长度
// 返回stream(流)当前的文件位置,如果发生错误返回-1. 
long ftell(FILE *stream);
// 为给出的流设置位置数据,fseek()成功时返回0,失败时返回非零. 
int fseek(FILE *stream, long offset, int origin);
origin的值应该是下列值其中之一:
SEEK_SET	从文件的开始处开始搜索
SEEK_CUR	从当前位置开始搜索
SEEK_END	从文件的结束处开始搜索

#include <stdio.h>
#include <string.h>

int gen_file(const char *path) {
	const char* content = "www.daozy.net";
	const unsigned cnt = 100;
	unsigned i = 0;
	FILE* fp = NULL;

	fp = fopen(path, "w");
	if (NULL == fp) {
		return -1;
	}
	for (i = 0; i < cnt; i++) {
		fputs(content, fp);
	}
	printf("write len = %u\n", strlen(content) * cnt);
	fclose(fp);
	return 0;
}

int file_len(const char *path) {
	FILE* fp = fopen(path, "r");
	if (NULL == fp) {
		return -1;
	}

	printf("0. ftell = %u\n", ftell(fp));
	// test 1
	fseek(fp, 10, SEEK_SET);
	printf("1. ftell = %u\n", ftell(fp));

	// test 2
	fseek(fp, 10, SEEK_CUR);
	printf("2. ftell = %u\n", ftell(fp));

	// test 3
	fseek(fp, 10, SEEK_END);
	printf("3. ftell = %u\n", ftell(fp));

	fseek(fp, 0, SEEK_END);
	printf("file length = %u\n", ftell(fp));

	fclose(fp);

	return 0;
}

int main() {
	const char* path = "36.txt";
	// gen_file(path);
	file_len(path);

	return 0;
}

fgetpos(),fsetpos()
// 保存给出的文件流(stream)的位置指针到给出的位置变量(position)中. position变量是fpos_t类型的(它在stdio.h中定义)并且是可以控制在FILE中每个可能的位置对象. fgetpos()执行成功时返回0,失败时返回一个非零值. 
int fgetpos(FILE *stream, fpos_t *position);
// 把给出的流的位置指针移到由position对象指定的位置. fpos_t是在stdio.h中定义的. fsetpos()执行成功返回0,失败时返回非零.
int fsetpos(FILE *stream, const fpos_t *position);
// 
void get_get_pos(const char* path) {
	FILE* fp = NULL;
	fpos_t position = 0;
	char buf[1024] = { 0 };

	fp = fopen(path, "r");
	if (NULL == fp) {
		return;
	}

	printf("ftell = %u\n", ftell(fp));
	fgets(buf, 32, fp);
	fgetpos(fp, &position);
	printf("1. fgetpos = %u\n", (unsigned)position);

	position = 64;
	fsetpos(fp, &position);
	fgets(buf, 32, fp);
	fgetpos(fp, &position);
	printf("2. fgetpos = %u\n", (unsigned)position);

	fclose(fp);
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

道知极限编程

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值