文章目录
一.为什么使用文件
二.什么是文件
三.文件的打开和关闭
四.文件的顺序读写
一.为什么使用文件
二.什么是文件
这里阿博在画图给友友们直观看一下它们的联系
三.文件的打开和关闭
首先给友友们介绍一下文件指针
图解分析
ANSIC 规定使用fopen函数来打开文件,fclose来关闭文件。
这里阿博给友友们总结一些比较常见的文件打开方式👀👀
代码解析
int main()
{
FILE* pf = fopen("text.txt", "w");
//FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
fclose(pf);
pf = NULL;
return 0;
}
刚才是相对路径下的文件,如果我们想打开桌面上的文件该如何处理呢
代码解析
int main()
{
//FILE* pf = fopen("C:\Users\86166\Desktop.txt", "r");
FILE* pf = fopen("C:\\Users\\86166\\Desktop.txt", "w");
if (pf == NULL)
{
perror("fopen");
return;
}
fclose(pf);
pf = NULL;
return 0;
}
四.文件的顺序读写
又到了传授内功的环节了🥷🥷
fputc的功能
代码解析
int main()
{
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
perror("fopen");
return;
}
//读文件
//把26个英文字母写到文件中
int i = 0;
for (i = 0; i < 26; i++)
{
fputc('a'+i, pf);
}
fclose(pf);
pf = NULL;
return 0;
}
fgetc的功能
代码解析
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
int ch = 0;
for (int i = 0; i < 26; i++)
{
ch = fgetc(pf);
printf("%c ", ch);
}
fclose(pf);
pf = NULL;
return 0;
}
疑惑解析
fputs的功能
代码解析
int main()
{
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
perror("fopen");
return;
}
fputs("i love you", pf);
fclose(pf);
pf = NULL;
return 0;
}
fgets的功能
代码解析
int main()
{
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
char arr[20] = { 0 };
fgets(arr,10, pf);
printf("%s\n", arr);
fclose(pf);
pf = NULL;
return 0;
}
fprintf的功能
代码解析
#include<stdio.h>
struct S
{
int n;
float f;
char arr[20];
};
int main()
{
struct S s = { 100,3.14f,"zhangsan" };
FILE* pf = fopen("text.txt", "w");
if (pf == NULL)
{
perror("fopen");
return;
}
fprintf(pf, "%d %f %s\n", s.n, s.f, s.arr);
fclose(pf);
pf = NULL;
return 0;
}
fscanf的功能
代码解析
struct S
{
int n;
float f;
char arr[20];
};
int main()
{
struct S s = {0};
FILE* pf = fopen("text.txt", "r");
if (pf == NULL)
{
perror("fopen");
return;
}
fscanf(pf, "%d %f %s\n", &(s.n),&(s.f), s.arr);
printf("%d %f %s", s.n, s.f, s.arr);
fclose(pf);
pf = NULL;
return 0;
}
sprintf的功能
sscanf的功能
代码解析
struct S
{
int n;
float f;
char arr[20];
};
int main()
{
struct S s = { 200,3.5f,"wangwu" };
//把一个结构体转换成字符串
char arr[200] = { 0 };
sprintf(arr, "%d %f %s\n", s.n, s.f, s.arr);
printf("字符串的数据:%s\n", arr);
struct S temp = { 0 };
sscanf(arr, "%d %f %s\n", &(temp.n) ,&(temp.f), temp.arr);
printf("格式化的数据:%d %f %s\n", temp.n, temp.f, temp.arr);
return 0;
}
这里阿博给友友们总结一下
好了友友们,本期内容讲到这里就结束了,下期阿博会完结文件知识,码字不易,可以给阿博点个关注哦,让我们下期再见💐💐💐 |