一、fopen:
1、函数原型:
FILE *fopen(const char *path, const char *mode);
功能:以特定的模式打开一个文件,并返回一个流指针;
返回值:成功:返回一个流指针 失败:返回EOF(-1)
path:需要打开的一个文件
mode:
r(read)或rb:打开只读文件;
r+或r+b:打开读写文件;
w(write)或w+b :打开只写文件,并且文件内容被清空。被打开文件不存在会自动创建一个;
w+或w+b:打开读写文件,并且文件内容被清空。被打开文件不存在会自动创建一个;
a(append) 或 ab :以追加的方式打开只写文件,被打开文件不存在会自动创建一个,若文件存在,追加数据会写在末尾,原有数据会保留;
a+ 或 a+b 或 ab+ :以追加的方式打开可读写文件,被打开文件不存在会自动创建一个,若文件存在,读取数据是从头读取;追加数据会写在末尾,原有数据会保留;
以上带有b(bin)的操作均是:以二进制方式打开文件。>>>>例如:
FILE *fp1 = fopen("3.c","r" );
FILE *fp2 = fopen("3.c","r+" );
FILE *fp3 = fopen("3.c","w" );
FILE *fp4 = fopen("3.c","w+" );
FILE *fp5 = fopen("3.c","a" );
FILE *fp6 = fopen("3.c","a+" );
二、fclose:
1、函数原型:
int flose(FILE *stream);
功能:关闭一个已经打开的流
返回值:成功返回0 失败:EOF 并设置errno(返回错误信息代码、错误号)
2、代码示例:
#include <stdio.h>
int main()
{
FILE *fp = fopen("3.c","r+");
if(fp == NULL)
printf("fp error\n");
else
printf("success\n");
int str = fclose(fp);//第一次关闭,操作成功
printf("%d\n",str);
printf("%d\n",fclose(fp));//第二关闭并打印返回值,错误操作
return 0;
}
3、运行结果:
可以看到文件打开成功,fclose第一次int str = fclose(fp);运行成功返回0;
fclose第二次运行printf("%d\n",fclose(fp));就报段错误了,表示已经free了属于非法操作
三、fflush:
1、函数原型:
int fflush(*stream):
功能:刷新操作,将未写完的的数据都被传入内核,能读取到并打印;
返回值:成功:0 失败:返回EOF(-1)并设值errno(错误代码信息)
stream:流指针
2、程序例子:
#include <stdio.h>
int main()
{
char buf[BUFSIZ];
printf("hello world");
fflush(stdout);//刷新输出流
while(1);
}
>>>可以打印出hello world,运行到死循环的地方,光标所在地方为死循环地方;
四、stdin、stdout、stderr:
1、stdin:标准输入流 0(与之相关联的整数描述符号)
2、stdout:标准输出流 1
3、stderr:标准错误 3