文章目录
一.fread和fwrite功能介绍
二.文件的随机读写
三.文本文件和二进制文件
四.文件读取结束的判定
五.文件缓冲区
一.fread和fwrite功能介绍
fwrite
代码解析
struct S
{
char name[20];
int age;
float score;
};
int main() //测试fwrite
{
struct S s = { "zhangsan",20,94.5f };
FILE* pf = fopen("text.dat", "wb");
if (pf == NULL)
{
perror("fopen");
return;
}
fwrite(&s, sizeof(struct S), 1, pf);
fclose(pf);
pf = NULL;
return 0;
}
fread
代码解析
struct S
{
char name[20];
int age;
float score;
};
int main() //测试fread
{
struct S s = {0};
FILE* pf = fopen("text.dat", "rb");
if (pf == NULL)
{
perror("fopen");
return;
}
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %f", s.name, s.age, s.score);
fclose(pf);
pf = NULL;
return 0;
}
二.文件的随机读写
fseek
代码解析
int main()
{
FILE* pf = fopen("text.dat", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
int ch = fgetc(pf);
printf("%c\n", ch); //a
ch = fgetc(pf);
printf("%c\n", ch); //b
ch = fgetc(pf);
printf("%c\n", ch); //c
ch = fgetc(pf);
printf("%c\n", ch); //d
//这次我们希望读到的是b
fseek(pf, -3, SEEK_CUR);
//fseek(pf,1,SEEK_SET);
//fseek(pf,-7,SEEK_END);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
ftell
代码解析
int main()
{
FILE* pf = fopen("text.dat", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
int ch = fgetc(pf);
printf("%c\n", ch); //a
ch = fgetc(pf);
printf("%c\n", ch); //b
ch = fgetc(pf);
printf("%c\n", ch); //c
ch = fgetc(pf);
printf("%c\n", ch); //d
这次我们希望读到的是b
//fseek(pf, -3, SEEK_CUR);
//ch = fgetc(pf);
printf("%d\n", ftell(pf));
fclose(pf);
pf = NULL;
return 0;
}
rewind
代码解析
int main()
{
FILE* pf = fopen("text.dat", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
int ch = fgetc(pf);
printf("%c\n", ch); //a
ch = fgetc(pf);
printf("%c\n", ch); //b
ch = fgetc(pf);
printf("%c\n", ch); //c
ch = fgetc(pf);
printf("%c\n", ch); //d
这次我们希望读到的是b
//fseek(pf, -3, SEEK_CUR);
//ch = fgetc(pf);
/*printf("%d\n", ftell(pf));*/
rewind(pf);
ch = fgetc(pf);
printf("%c\n", ch);
fclose(pf);
pf = NULL;
return 0;
}
三.文本文件和二进制文件
代码解析
int main()
{
int a = 10000;
FILE* pf = fopen("test.txt", "wb");
fwrite(&a, 4, 1, pf);//二进制的形式写到文件中
fclose(pf);
pf = NULL;
return 0;
}
四.文件读取结束的判定
五.文件缓冲区
代码解析
#include <stdio.h>
#include <windows.h>
int main()
{
FILE* pf = fopen("test.txt", "w");
fputs("abcdef", pf);//先将代码放在输出缓冲区
printf("睡眠10秒-已经写数据了,打开test.txt文件,发现文件没有内容\n");
Sleep(10000);
printf("刷新缓冲区\n");
fflush(pf);//刷新缓冲区时,才将输出缓冲区的数据写到文件(磁盘)
//注:fflush 在高版本的VS上不能使用了
printf("再睡眠10秒-此时,再次打开test.txt文件,文件有内容了\n");
Sleep(10000);
fclose(pf);
//注:fclose在关闭文件的时候,也会刷新缓冲区
pf = NULL;
return 0;
}
好了友友们,文件的内容到这里就告一段落了,希望友友们能够有所收获,真正的掌握文件,码字不易,友友们可以给阿博点个关注哦,后续阿博会继续分享干货知识,让我们下期再见.🌺🌺🌺 |