1. 打开文件
函数原型 FILE * fopen(const char *filename ,const char *openstyle);
a 第一个参数为要打开的文件的名字;
b 第二个为打开文件的方式;
c 返回值类型为FILE* FILE是一个结构体(关于文件信息的数据包);
d 当打开文件失败时返回空指针NULL。
1.2 打开方式可选参数及介绍
“r”打开文本文件,可以读取文件,该文件必须存在。
“w”打开文本文件可以写入文件,先将文件长度截为0,如果文件不存在则先创建。
“a”打开文本文件,可以写入文件,向已有文件尾追加内容,不存在则先创建。
“r+”打开文本文件,可以读取写入文件,该文件必须存在。
“w+”打开文本文件,可以读取写入文件,如果存在先将长度截为0,否则先创建。
“a+”打开文本文件,可以读取写入文件,向已有文件尾追加内容,如果不存在则创建,写入时只能追加。
加入b字符是用来告诉函数库打开的文件为二进制文件,而非纯文字文件。“rb”,“wb”,“ab”,“ab+”,“a+b”,“wb+”,“w+b”,“ab+”,“a+b”,与前面模式类似只能使用二进制模式打开文件。
注意:使用任意一种“w”模式打开已有文件,文件内容将会被删除,以便程序以一个空文件开始操作。
2, 关闭文件 函数原型:int fclose(FILE *)
a)参数为文件指针
b)返回值 如果关闭成功返回0,否则返回EOF
3, 标准文件 文件指针 一般使用的设备
标准输入 stdin 键盘
标准输出 stdout 显示器
标准错误 stderr 显示器
4, fprintf(),printf(),sprintf()
a) printf,是把格式字符串输出到标准输出。
b) sprintf,是把字符串输出到指定字符串中,所以参数比printf多出一个 char* 。那就是目标字符串地址。
c) fprintf,是把格式字符串输出到指定文件设备中,所以参数比printf多一个文件指针FILE *。
5, fscanf(),scanf(),sscanf()
a) scanf,从控制台输入
b) fscanf,从文件输入
c) sscanf,从指定字符串输入
例如:
#include <stdio.h>
#include <stdlib.h>
int main(int argc, const char * argv[])
{
# define MAX 40
FILE* fp;
char words[MAX];
if((fp=fopen("words","W+"))==NULL)
{
fprintf(stdout, "Can not open\"words\"file\n");
exit(1);
}
puts("Enter words to add to the file:press the Enter");
puts("Key at the begining of a line to terminate.");
while (gets(words)!=NULL && words[0]!='\0')
{
fprintf(fp, "%s",words);
}
puts("File contents:");
rewind(fp);//回到文件开始处
while (fscanf(fp, "%s",words)==1)
{
puts(words);
}
if(fclose(fp)!=0)
{
fprintf(stderr, "Error closing file\n");
}
return 0;
}