立即学习: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);
}