1.使用文件我们可以将数据直接存放在电脑的硬盘上,做到了数据的持久化
2.磁盘上的文件,但是在程序设计中,我们一般谈的文件有两种:程序文件、数据文件
3.程序文件包括:源程序文件(后缀为.c),目标文件(windows环境后缀为.obj),可执行程序(windows环境后缀为.exe)
4.数据文件:内容不一定是程序,而是程序运行时读写的数据,比如程序运行需要从中读写数据的文件,或者输入内容的文件
目录
文件顺序读、写函数:fputc,fgetc,fputs,fgets
关于文件读、写的函数
文件指针
每打开一个文件,都会开辟一个 FILE 类型的结构变量的文件信息区,该结构体类型是具有系统声明的
fopen,fclose - 文件打开和关闭
int main()
{
//打开文件
FILE* pf = fopen("test.dat","w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
文件顺序读、写函数:fputc,fgetc,fputs,fgets
二进制读、写: fwrite,fread
对格式化的数据进行读、写:fscanf,fprintf
1.fputc
FILE* pf = fopen("test.dat", "w");
fputc('b', pf);
2.fgetc
FILE* pf = fopen("test.dat", "r");
//读文件
int ret = fgetc(pf);
printf("%c\n", ret);
3.fputs
FILE* pf = fopen("test.dat", "w");
//写文件 - 按照行来写
fputs("abcdef\n",pf);
4.fgets
char arr[10] = {0};
FILE* pf = fopen("test.dat", "r");
//读文件
fgets(arr, 4, pf);
printf("%s\n", arr);
5.fprintf
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = { "abcdef",10,5.5f };
//对格式化的数据进行写文件
FILE* pf = fopen("test.dat", "w");
if (NULL == pf)
{
perror("fopen");
return 1;
}
//写文件
fprintf(pf,"%s %d %f",s.arr,s.num,s.sc);
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
6.fscanf
int main()
{
struct S s = { 0 };
//对格式化的数据进行写文件
FILE* pf = fopen("test.dat", "r");
if (NULL == pf)
{
perror("fopen");
return 1;
}
//读文件
fscanf(pf,"%s %d %f", s.arr, &(s.num), &(s.sc));
//打印
fprintf(stdout,"%s %d %f\n", s.arr, s.num, s.sc);
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
7.fwrite
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = { "abcde",10,5.5f };
//二进制形式写
FILE* pf = fopen("test.dat", "w");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//写文件
fwrite(&s, sizeof(struct S), 1, pf);
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
8.fread
struct S
{
char arr[10];
int num;
float sc;
};
int main()
{
struct S s = { 0 };
//二进制形式读
FILE* pf = fopen("test.dat", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//读文件
fread(&s, sizeof(struct S), 1, pf);
printf("%s %d %f\n", s.arr, s.num, s.sc);
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}
文件随机读、写的函数
fseek
SEEK_CUR 当前位置
SEEK_END 末尾位置,只能是负数
SEEK_SET 起始位置
ftell
rewind
让文件指针回到起始位置
int main()
{
FILE* pf = fopen("test.txt", "r");
if (pf == NULL)
{
perror("fopen");
return 1;
}
//读文件
int ch = fgetc(pf);
printf("%c\n", ch);
//调整文件指针
fseek(pf, -1, SEEK_CUR);//从当前位置
fseek(pf, -2, SEEK_END);//从末尾位置,只能是负数
fseek(pf, -1, SEEK_SET);//从起始位置
int ch = fgetc(pf);
printf("%c\n", ch);
int ch = fgetc(pf);
printf("%c\n", ch);
int ret = ftell(pf);
printf("%d\n", ret);
//让文件指针回到起始位置
rewind(pf);
int ch = fgetc(pf);
printf("%c\n", ch);//a
//关闭文件
fclose(pf);
pf = NULL;
return 0;
}