Linux文件IO和标准IO

Linux 文件IO

Linux中做文件IO最常用到的5个函数是: open , close , read , write 和 lseek ,不是ISO C的组成部分,这5个函数是不带缓冲的IO,也即每个read和write都调用了内核的一个系统调用。

#include <fcntl.h>
#include <unistd.h>
int open(const char *pathname, int oflag, ... /* mode_t mode */);/* 成功返回文件描述符, 失败返回-1 */
int close(int filedes);/* 成功返回0, 失败返回-1 */
off_t lseek(int filedes, off_t offset, int whence);/* 成功返回新的文件偏移量,出错返回-1 */
ssize_t read(int filedes, void *buf, size_t nbytes);/* 成功则返回读取到的字节数,若已到文件的结尾返回0,出错返回-1 */
ssize_t write(int filedes, void *buf, size_t nbytes);/* 成功则返回写入的字节数,出错返回-1 */

Linux 标准IO

标准IO库提供缓冲功能,减少系统调用。

  • 全缓冲。即填满IO缓冲区后才进行IO操作。
  • 行缓冲。遇到换行符时执行IO操作。 * 无缓冲。

一般情况下,标准出错无缓冲。如果涉及终端设备,一般是行缓冲,否则是全缓冲。
可用 setbuf 和 setvbuf 函数设置缓冲类型已经缓冲区大小,使用fflush函数冲洗缓冲区。

打开流

使用 fopen , freopen , fdopen 三个函数打开一个流,这三个函数都返回FILE类型的指针。

#include <stdio.h>
FILE *fopen(const char *restrict pathname, const char *restrict type);
FILE *freopen(const char *restrict pathname, const char *restrict type, FILE *restrict fp);
FILE *dopen(int filedes, const char *type);
/* 成功返回FILE类型指针,出错返回NULL */
  • fopen 打开一个指定的文件。
  • freopen 在一个指定的流上打开一个文件,比如在标准输出流上打开某文件。
  • dopen 打开指定的文件描述符代表的文件。常用于读取管道或者其他特殊类型的文件,因为这些文件不能直接用fopen打开。
  • type 参数指定操作类型,入读写,追加等等。

关闭流

fclose 函数关闭一个流:

#include <stdio.h>
int flose(FILE *fp);
/* 成功返回0,出错返回EOF */

读写流

  • 每次一个字符的IO流
#include <stdio.h>
/* 输入 */
int getc(FILE *fp);
int fgetc(FILE *fp);
int getchar(void);
/* 上面三个函数的返回值为int,因为EOF常实现为-1,返回int就能与之比较 */

/* 判断出错或者结束 */
int ferror(FILE *fp);
int feof(FILE *fp);
void clearerr(FILE *fp); /* 清除error或者eof标志 */

/* 把字符压送回流 */
int ungetc(intc FILE *fp);

/* 输出 */
int putc(int c, FILE *fp);
int fputc(int c, FILE *fp);
int putchar(int c);
  • 每次一行的IO流
#include <stdio.h>
/* 输入 */
char *fgets(char *restrict buf, int n, FILE *restrict fp);
char *gets(char *buf);
/* gets由于没有指定缓冲区,所以有可能造成缓冲区溢出,要小心 */

/* 输出 */
int fputs(char *restrict buf, FILE *restrict fp);
int puts(const char *buf);
  • 二进制读取读写文件流,常作为读取打开的整个流文件
#include <stdio.h>
size_t fread(void *restrict ptr, size_t size, size_t nobj,FILE *restrict fp);
size_t fwrite(const void *restrict ptr, size_t size, size_t nobj,FILE *restrict fp);
/* 返回值:读或写的对象数 */

定位流

#include <stdio.h>
long ftell(FILE *fp);
/* 成功则返回当前文件位置指示,出错返回-1L */

int fseek(FILE *fp, long offset, int whence);
/* 成功返回0, 出错返回非0 */

int fgetpos(FILE *restrict fp, fpos_t *restrict pos);
int fsetpos(FILE *fp, fpos_t *pos);
/* 成功返回0,出错返回非0 */

格式化输出IO流

执行格式化输出的主要是4个 printf 函数:

  • printf 输出到标准输出
  • fprintf 输出到指定流
  • sprintf 输出到指定数组
  • snprintf 输出到指定数组并在数组的尾端自动添加一个null字节

格式化输入IO流

格式化输入主要是三个 scanf 函数:

  • scanf 从标准输入获取
  • fscanf 从指定流获取
  • sscanf 从指定数组获取

猜你喜欢

转载自blog.csdn.net/vanturman/article/details/84036935