一、文件流
1. 已打开文件的标志
2. fopen函数成功后得到文件流
3. FILE类型的指针
4. 包含四个成员
文件描述符
出错标志
缓冲区地址
缓冲区大小
二、标准IO基本函数
1. 打开流
FILE *fopen(const char *path, const char *mode);
path:打开文件的地址,mode:打开文件的方式
"r" 只读 | 文件流指向文件开头 |
"w" 只写 | 文件流指向文件开头,文件不存在创建,存在将文件截短为0 |
"r+" 读写 | 文件流指向开头 |
"w+" 读写 | 文件流指向开头, 文件不存在创建,存在将文件截短为0 |
"a" 追加写 | 文件流指向末尾,文件不存在创建 |
"a+" 开头读,末尾写 | 文件不存在创建 |
2.读写
1、按行读写
char *fgets(char *buf, int size, FILE *fp);
功能:从fp中读取size-1个字节到buf中,遇到'\n'会停止。
成功返回buf的地址,失败或读到文件结尾返回值NULL,所以要使用ferror判断
int fputs(const char *buf, FILE *fp);
功能:将buf中的整个字符串,写入fp文件
成功返回写入的字节数,(出错返回EOF,不判断)
2、按字符读写
int fgetc(FILE *fp)`
功能: 从fp文件读取一个字符,转换为整型返回
读完或者出错返回EOF,if判断ferror或者读完
int fputc(int c, FILE *fp)`
功能:将c写入文件fp
正确返回c的ASCII值,出错返回EOF,不判断
3、按结构
int fread(char *buf, int size, int nmemb, FILE *fp);`
功能:从fp文件读nmemb元素结构,每个元素size字节,到buf
成功将读到的成员个数返回,如果读到文件结束标志或者出错都返回0
int fwrite(const char *buf, int size, int nmemb, FILE *fp);
功能:将buf中,每个成员size字节,nmemb元素写入fp文件
成功执行则返回实际写入的数据块数目,失败显示一个错误
3.文件流
int fseek(FILE *fp, long size, int whence);
将fp文件的文件流,从whence(SEEK_SET开头/SEEK_END末尾/SEEK_CUR当前)位置偏移size字节
long ftell(FILE *stream); 文件位置指针当前位置相对于文件首的偏移字节数
void rewind(FILE *stream); 文件流指针指向开头
4.其他函数
int feof(FILE *stream);遇到文件结束标志返回非零 feof()原理和用法
errno:返回系统最后一次的错误代码
三、关于缓冲
1. 类型
全缓存
行缓存 stdin stdout
无缓存 stderr
2. 如何刷新缓冲区
行缓存遇到'\n'
全缓存写满(4096)
进程终止
int fflush(FILE *stream)(3)使用函数刷新缓冲区
四、练习
#include <stdio.h>
#define BUFSIZE 16
int main(int argc, char *argv[])
{
FILE *fp;
char buf[BUFSIZE] = {};
if (argc < 2)
return 1;
fp = fopen(argv[1], "r");
if (NULL == fp) {
fprintf(stderr, "fopen() failed\n");
return 1;
}
fseek(fp, -10, SEEK_END);
printf("ftell:%ld\n", ftell(fp));
fread(buf, 1, BUFSIZE, fp);
printf("after read ftell:%ld\n", ftell(fp));
rewind(fp);
printf("after rewind ftell:%ld\n", ftell(fp));
fputs(buf, stdout);
fclose(fp);
return 0;
}