UNIX环境高级编程读书笔记-五

本章主要介绍标准I/O库

标准I/O库

流和FILE对象

流的定向分类:

1. 单字节I/O
2. 宽字节I/O

更改流定向:

  1. 清楚流定向: freopen
  2. 设置流定向: fwide
1
2
3
4
#include <stdio.h>
#include <wchar.h>
int fwide(FILE *fp, int mode);
\\ 返回值: 宽定向返回正值, 字节定向,返回负值, 未定向的, 返回0

mode 参数值为负: fwide试图指定流是字节定向

mode 参数值为正: fwide试图指定流是宽字节定向的

mode 参数值为0: 不设置流的定向

标准输入输出,标准错误

缓冲

stderr : 不带缓冲, 使得出错信息尽快显示出来

若是指向终端设备的流, 则是行缓冲的; 否则是全缓冲的

更改缓冲:

1
2
3
4
# include <stdio.h>

void setbuf(FILE *restrict fp, char *restrict buf);
int setvbuf(FILE *restrict fp, char *restrict buf. int mode, size_t size);

setbuf: 控制开关缓冲 buf 缓冲区长度

setvbuf: 设置缓冲类型

​ mode:

  • _IOFBF 全缓冲
  • _IOLBF 行缓冲
  • _IONBF 不带缓冲

强行冲洗一个流:

1
2
#include <stdio.h>
int fflush(FILE *fp);

打开流

1
2
3
4
#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 *fdopen(int fd, const char *type);

流的读写

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// 输入函数
int getc(FILE *fp); // 用宏实现的, 快
int fgetc(FILE *fp);
int getchar(void); //getc(stdio)

int ferror(FILE *fp);
int feof(FILE *fp);
void clearerr(FILE *fp);

int ungetc(int c, FILE *fp); //回送字符

// 输出函数

int putc(int c, FILE *fp);
int fputc(int c, FILE *fp);
int putchar(int intc);

二进制I/O

1
2
size_t fread(void *restrict ptr, size_t nobj, FILE *restrict fp);
size_t fwrite(const void *restrict ptr, size_t size, size_t nobj, FILE *restrict fp);

定位流

1
2
3
4
5
long ftell(*fp);
int fseek(FILE *fp, long offset, int whence);
// ISO C 标准
int fsetpos
int fgetpos

格式化I/O

  1. 格式化输出

    1
    2
    3
    4
    5
    6
    #include <stdio.h>
    int printf(const char *restrict format);
    int fprintf(FILE *restrict fp, const char *restrict format, ...);
    int dprintf(int fd, const char *restrict format, ...);
    int sprintf(char *restrict buf, const char *restrict format, ... );
    int snprintf(char *restrict buf, size_t n, const char *restrict format, ...);
  2. Vprintf

  3. 格式化输入

    1
    2
    3
    int scanf(const char *restrict format, ... );
    int fscanf(FILE *restrict fp, const *restrict format, ...);
    int sscanf(const char *restrict buf, const char *restrict format, ...);
  4. 获得描述符

    1
    int fileno(FILE *fp);

临时文件

1
2
3
4
5
6
char *tmpnam(char *ptr);
FILE *tmpfile(void); //程序结束后会被删除
// XSI
#include <stdlib.h>
char *madtemp(char *template); // 指向目录名的指针
char *mkstemp(char *template); // 文件描述符

内存流