如果向了解那8个函数的话,可以登录下面的网站,自行登录。
fgetc - C++ Referencehttps://legacy.cplusplus.com/reference/cstdio/fgetc/?kw=fgetc
- 对于一个代码而言,程序中的数据是不能保存在内存中的,那就需要文件操作来保存这一部分的数据,也就是持久性的保存。
#include<stdio.h> int main() { int a = 0; scanf("%d",&a); printf("%d\n",a); return 0; }
对于这一个代码,输入一个数,就会打印一个数,单数打印过后,内存中又变为零,这就需要文件的打开和关闭来实现。
-
对于代码来说,fopen函数来代表打开文件,fclose函数代表关闭文件。fopen的表达式为:FILE * fopen ( const char * filename, const char * mode );fclose的表达式为:int fclose ( FILE * stream );
-
对于打开文件和关闭文件的代码,则代码为:
int mian() { //打开文件 FILE*pf = fopen("test.txt", "w"); if (pf == NULL) { perror("fopen"); } //读文件 //关闭文件 fclose(pf);//野指针 pf = NULL; return 0; }
这就是打开文件和关闭文件的代码,中间一部分就是读代码,
-
⽂件的顺序读写:这部分就是读文件的这一部分,它包含8个函数,我们来一一介绍。上述就是这8个函数,
-
首先介绍的就是fputc函数,它的表达式为:int fputc ( int character, FILE * stream );返回类型为int。则代码为:
//fputc函数代码 //文件的打开和关闭 int mian() { //打开文件 FILE* pf = fopen("test.txt", "w"); if (pf == NULL) { perror("fopen"); } //读文件 //打印a,b,c, /*fputc('a',pf); fputc('b', pf); fputc('c', pf);*/ //在文件中打印26个字母 char ch = 0; for (ch = 'a'; ch <= 'z'; ch++) { fputc(ch, pf); } //关闭文件 fclose(pf);//野指针 pf = NULL; return 0; }
这个是字符输出函数,因为打开文件的代码中有‘w’,代表输出数据,‘r’,代表输入数据。
-
fgetc的函数:它的表达式为:int fgetc ( FILE * stream );,返回类型为int。fgetc代表输入函数。
//fgetc的函数,字符输入函数 int mian() { //打开文件 FILE* pf = fopen("test.txt", "r"); if (pf == NULL) { perror("fopen"); } //读文件 //打印test.txt中的字符 /*int ch = fgetc(pf); printf("%c\n", ch); ch = fgetc(pf); printf("%c\n", ch); ch = fgetc(pf); printf("%c\n", ch);*/ int ch = 0; while ((ch = fgetc(pf)) != EOF) { printf("%c\n", ch); } //关闭文件 fclose(pf);//野指针 pf = NULL; return 0; }
我们先讲两个,先巩固一下。