小甲鱼 P59 随机读写文件
ftell()函数:获取位置指示器的值
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//ftell返回值是long类型
FILE *fp;
if ((fp = fopen("hello.txt", "w")) == NULL)
{
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
printf("%ld\n", ftell(fp));
fputc('F', fp);
printf("%ld\n", ftell(fp));
fputs("ishC\n", fp);
printf("%ld\n", ftell(fp));
fclose(fp);
return 0;
}
rewind()函数:将位置指示器移到文件头的位置
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
//ftell返回值是long类型
FILE *fp;
if ((fp = fopen("hello.txt", "w")) == NULL)
{
printf("文件打开失败!\n");
exit(EXIT_FAILURE);
}
printf("%ld\n", ftell(fp));
fputc('F', fp);
printf("%ld\n", ftell(fp));
fputs("ishC\n", fp);
printf("%ld\n", ftell(fp));
//把当前位置指示器初始化到文件头的位置
rewind(fp);
fputs("Hello", fp);
fclose(fp);
return 0;
}
fseek(FILE *stream, long int offset, int whence)
用于设置文件流的位置指示器
offset:指定从whence参数的位置起偏移多少个字节
扫描二维码关注公众号,回复:
3581617 查看本文章
whence:SEEK_SET(文件头),SEEK_CUR(当前的读写位置),SEEK_END(文件末尾)
实现一个程序,先要求录入学生的姓名、学号和成绩在指定文件中,并且直接读取第二条数据显示到屏幕上。
#include <stdio.h>
#include <stdlib.h>
#define N 4
struct Stu
{
char name[24];
int num;
float score;
}stu[N], sb;
int main(void)
{
FILE *fp;
int i;
if ((fp = fopen("score.txt", "wb")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
printf("请开始录入成绩(格式:姓名 学号 成绩)");
for (i = 0; i < N; i++)
{
scanf("%s %s %f", stu[i].name, &stu[i].num, &stu[i].score);
}
//使用二进制来写入函数
fwrite(stu, sizeof(struct Stu), N, fp);
fclose(fp);
if ((fp = fopen("score.txt", "rb")) == NULL)
{
printf("打开文件失败!\n");
exit(EXIT_FAILURE);
}
//从文件头开始偏移一个结构体的位置,打印第二个结构体
fseek(fp, sizeof(struct Stu), SEEK_SET);
fread(&sb, sizeof(struct Stu), 1, fp);
printf("%s(%d)的成绩是:%.2f\n", sb.name, sb.num, sb.score);
fclose(fp);
return 0;
}