一.文件的打开与关闭
c程序针对输入输出操作都是通过流来进行的。
stdin标准输⼊流,在⼤多数的环境中从键盘输⼊,scanf函数就是从标准输⼊流中读取数据。
stdout标准输出流,⼤多数的环境中输出⾄显⽰器界⾯,printf函数就是将信息输出到标准输出
流中。
stderr标准错误流,⼤多数环境中输出到显⽰器界⾯。
以上三个流的类型称为FILE*,通常称为文件指针
//打开⽂件
FILE * fopen ( const char * filename, const char * mode );
//关闭⽂件
int fclose ( FILE * stream );
fopen与fclose被ascall规定为打开文件与关闭文件的函数
打开文件操作需要分成读和写,一个是打开文件并读取,一个是打开文件并写入,功能不同具体操作需根据情况而定。
#include <stdio.h>
int main ()
{
FILE * pFile;
//打开⽂件
pFile = fopen ("myfile.txt","w");
//⽂件操作
if (pFile!=NULL)
{
fputs ("fopen example",pFile);
//关闭⽂件
fclose (pFile);
}
return 0;
}
二.文件读写函数
scanf/fscanf/sscanf
printf/fprintf/sprintf
sscamf从一个字符中读入与指定格式相符的数据。
sprintf吧变量打印到字符串,从而获得数字的字符形式。
fscanf适用于所有输入流
fprintf适用于所有输出流
三.⽂件的随机读写
fseek
根据⽂件指针的位置和偏移量来定位⽂件指针
int fseek ( FILE * stream, long int offset, int origin );
l例如
int main ()
{
FILE * pFile;
pFile = fopen ( "example.txt" , "wb" );
fputs ( "This is an apple." , pFile );
fseek ( pFile , 9 , SEEK_SET );
fputs ( " sam" , pFile );
fclose ( pFile );
return 0;
}
4 5 6 7 8 9
10
11
12
13
fseek可以返回文件指针的位置偏移量
long int ftell ( FILE * stream );
ftell可以返回文件指针对起始位置偏移量
rewind让⽂件指针的位置回到⽂件的起始位置