1、FILE *fopen(char *path,*mode);
mode:
r: 读打开, 不创建
w: 写打开,创建/清空
a: 写打开, 创建/追加
r+: 读/写打开,不创建
w+:读/写打开,创建/清空
a+:读/写打开, 创建/追加
衍生:
rb,rb+,wb,wb+,ab,ab+; 对二进制操作
rt,rt+,wt,wt+,at,at+; 对文本文件操作
2、例程说明:
#include
#include
#include
#define filelen 10
int main()
{
int ret,i;
FILE * fp = fopen("test","w+"); //读/写打开,创建/清空
char buf_w[filelen] = {"HeLlow!"};
for(i=0;i
printf("[%d] %c ",i,buf_w[i]);
}
//打印 [0] H [1] e [2] L [3] l [4] o [5] w [6] ! [7] [8] [9]
char buf_r[filelen];
ret = fwrite(buf_w,sizeof(char),filelen,fp); //此时文件指针已经到了文件尾部
printf("fwrit: %d\n",ret);
rewind(fp); //将文件指针置于文件头部
memset(buf_r,0,sizeof(buf_r));
ret = fread(buf_r,sizeof(char),filelen,fp); //此时文件指针再次到了尾部
printf("fread: %d\n",ret);
for(i=0;i
printf("[%d] %c ",i,buf_r[i]);
}
//打印 [0] H [1] e [2] L [3] l [4] o [5] w [6] ! [7] [8] [9]
ret = fseek(fp,0,SEEK_SET); //将文件指针置于距离 头部 偏移量 为 0 的位置,等同于rewind()
memset(buf_r,0,sizeof(buf_r));
ret = fread(buf_r,sizeof(char),filelen,fp); //文件指针到达文件尾部
printf("1 ret:%d buf_r[0]:%c\n",ret,buf_r[0]);
//打印 1 ret:10 buf_r[0]:H
fseek(fp,-4,SEEK_CUR); //文件指针尾部向前偏移 4
memset(buf_r,0,sizeof(buf_r));
ret = fread(buf_r,sizeof(char),filelen,fp); //文件指针到达文件尾部
printf("2 ret:%d buf_r[0]:%c\n",ret,buf_r[0]);
//打印 2 ret:4 buf_r[0]:!
fseek(fp,0,SEEK_END); //文件指针置于尾部
memset(buf_r,0,sizeof(buf_r));
ret = fread(buf_r,sizeof(char),filelen,fp);
printf("3 ret:%d buf_r[0]:%c\n",ret,buf_r[0]);
//打印 3 ret:0 buf_r[0]:
// 打印 4 ret:10
fclose(fp);
程序运行结果:
[0] H [1] e [2] L [3] l [4] o [5] w [6] ! [7] [8] [9] fwrit: 10 fread: 10 [0] H [1] e [2] L [3] l [4] o [5] w [6] ! [7] [8] [9] 1 ret:10 buf_r[0]:H 2 ret:4 buf_r[0]:! 3 ret:0 buf_r[0]: 4 ret:10