Unix I/O
使用标准IO的一个优点是不用考虑缓冲和最佳IO长度问题
缓冲
- 全缓冲
- 行缓冲
- 不带缓冲
int fflush(FILE *fp);//可以强制冲洗缓冲区
打开流
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);
int fclose(FILE *fp);//关闭流
读写流
按字符
读:
int getc(FILE *fp);
int fgetc(FILE *fp);
int getchar(void); // 相当于getc(STDIN);
值得注意的是,不管是出错还是到文件结尾,3个函数返回值都相同。区别这两种情况,必须调用ferror
或feof
;
#include <stdio.h>
int main(){
int c;
while((c = getc(stdin)) != EOF) {
if (putc(c, stdout) == EOF) {
fprintf(stderr, "output error");
}
}
if (ferror(stdin)) { //判断是EOF还是error
fprintf(stderr, "input error");
}
}
写:
int putc(int c, FILE *fp);
int fputc(int c, FILE *fp);
int putchar(int c);//相当于putc(c, stdout);
按行
char *fgets(char *restrict buf, int n, FILE *restrict fp);
char *gets(char *buf); //不考虑缓冲区长度读,可能溢出
char fputs(const char *restrict str, FILE *restrict fp);
int puts(const char *str);
二进制IO
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);
写一个结构到文件中:
struct {
short count;
long total;
char name[NAMESIZE];
} item;
if (fwirte(&item, sizeof(item), 1, fp) != 1) {
fprintf(stderr, "fwirte error");
}