本章以stream(区别开STREAMS)为中心,讲解了UNIX的标准I/O库。
stream的核心是FILE结构。
打开一个stream时,fopen返回一个FILE对象指针。该FILE结构包括了:
实际用于I/O的文件描述符,指向该流缓冲区的指针,缓冲区的长度,当前缓冲区的字符,以及出错标志等等。
FILE结构定义在/usr/include/stdio.h中。
typedef struct _IO_FILE FILE;
_IO_FILE结构定义在/usr/include/libio.h中。
View Code
1 struct _IO_FILE { 2 int _flags; /* High-order word is _IO_MAGIC; rest is flags. */ 3 #define _IO_file_flags _flags 4 5 /* The following pointers correspond to the C++ streambuf protocol. */ 6 /* Note: Tk uses the _IO_read_ptr and _IO_read_end fields directly. */ 7 char* _IO_read_ptr; /* Current read pointer */ 8 char* _IO_read_end; /* End of get area. */ 9 char* _IO_read_base; /* Start of putback+get area. */ 10 char* _IO_write_base; /* Start of put area. */ 11 char* _IO_write_ptr; /* Current put pointer. */ 12 char* _IO_write_end; /* End of put area. */ 13 char* _IO_buf_base; /* Start of reserve area. */ 14 char* _IO_buf_end; /* End of reserve area. */ 15 /* The following fields are used to support backing up and undo. */ 16 char *_IO_save_base; /* Pointer to start of non-current get area. */ 17 char *_IO_backup_base; /* Pointer to first valid character of backup area */ 18 char *_IO_save_end; /* Pointer to end of non-current get area. */ 19 20 struct _IO_marker *_markers; 21 22 struct _IO_FILE *_chain; 23 24 int _fileno; 25 #if 0 26 int _blksize; 27 #else 28 int _flags2; 29 #endif 30 _IO_off_t _old_offset; /* This used to be _offset but it's too small. */ 31 32 #define __HAVE_COLUMN /* temporary */ 33 /* 1+column number of pbase(); 0 is unknown. */ 34 unsigned short _cur_column; 35 signed char _vtable_offset; 36 char _shortbuf[1]; 37 38 /* char* _save_gptr; char* _save_egptr; */ 39 40 _IO_lock_t *_lock; 41 #ifdef _IO_USE_OLD_IO_FILE 42 };
本章主要内容总结如下图:
零散知识点:
char *tmpnam(char *ptr) tmpnam产生一个与现有文件名不同的一个有效路径字符串。
FILE *tmpfile(void) /*产生临时二进制文件*/ 在进程结束时自动删除。
char *tempnam(const char *directory,const char *prefix) 为产生的路径名指定目录和前缀。
没看懂的问题:
对标准I/O流如何使用fsync函数(为什么数据在内核缓冲区时,调用fsync没效果)