1.文件类型指针:
文件类型指针简称文件指针,文件指针的创建:
FILE *pf;
2.文件的打开与关闭:
文件的打开需要用到fopen函数,文件的关闭需要用到fclose函数
FILE * fopen ( const char * filename, const char * mode )
int fclose ( FILE * stream );
mode是文件的打开模式,以下都是文件的打开模式:
代码展示:
#include <stdio.h>
int main()
{
FILE* pFile;
pFile = fopen("test.txt", "w");
if (pFile != NULL)
{
fputs("File Exam", pFile);
fclose(pFile);
}
return 0;
}
这里只展示了‘w'的用法,其余的还需要各位直接去亲自练练。
3.文件的顺序读写
顺序读写函数:
fgets函数:从文本文件中读取数据
char * fgets ( char * str, int num, FILE * stream );
代码展示:
#include <stdio.h>
int main()
{
FILE * pFile;
char mystring [10];
pFile = fopen ("myfile.txt" , "r");
if (pFile == NULL) perror ("Error opening file");
else {
if ( fgets (mystring , 100 , pFile) != NULL )
puts (mystring);
fclose (pFile);
}
return 0;
}
结果展示:
fputs函数:将数据输出到文本文件中
int fputs ( const char * str, FILE * stream );
代码展示:
#include <stdio.h>
int main()
{
FILE* pFile;
char sentence[13];
printf("Enter sentence to append: ");
fgets(sentence, 13, stdin);
pFile = fopen("mylog.txt", "a");
fputs(sentence, pFile);
fclose(pFile);
return 0;
}
结果展示:
举例到这,其它还需自行体会。