深入int getc(FILE *fp),putc(int c, FILE *fp),int getchar(void),int putchar(int c)
这几个其实都不是函数,仅仅是在stdio.h头文件中定义的宏
#define putc(_c,_stream) (--(_stream)->_cnt >= 0 \
? 0xff & (*(_stream)->_ptr++ = (char)(_c)) : _flsbuf((_c),(_stream)))
#define putchar(_c) putc((_c),stdout)
#define getc(_stream) (--(_stream)->_cnt >= 0 \
? 0xff & *(_stream)->_ptr++ : _filbuf(_stream))
? 0xff & *(_stream)->_ptr++ : _filbuf(_stream))
#define putc(_c,_stream) (--(_stream)->_cnt >= 0 \
? 0xff & (*(_stream)->_ptr++ = (char)(_c)) : _flsbuf((_c),(_stream)))
#define getchar() getc(stdin)
#define putchar(_c) putc((_c),stdout)
为了深入了解这些宏定义,首先要熟悉他们的参数FILE
#ifndef _FILE_DEFINED
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
#define _FILE_DEFINED
#endif
struct _iobuf {
char *_ptr;
int _cnt;
char *_base;
int _flag;
int _file;
int _charbuf;
int _bufsiz;
char *_tmpfname;
};
typedef struct _iobuf FILE;
#define _FILE_DEFINED
#endif
由此可见FILE即是struct _iobuf ,是定义的一个结构体类型。
观察getc()和putc()函数,这里只用了FILE类型中的_cnt和_ptr两个参数,分别表示IO流中的字符的总数和下一个字符的位置。
同时其中用到了_filbuf()和_flsbuf()
_CRTIMP int __cdecl _filbuf(FILE *);
_CRTIMP int __cdecl _flsbuf(int, FILE *);
_CRTIMP int __cdecl _flsbuf(int, FILE *);
这两个函数应该是处理文件读完和写完的操作,个人感觉可能_filbuf是将缓冲区中的字符写到FILE里面,_flsbuf是将已到缓冲区但尚未写到文件中的数据写到文件中。
但还没研究出来是怎么工作的,后面搞定了的话会补充上。
浙公网安备 33010602011771号