词条 | getc |
释义 | 函数名: getc 功 能: 从流中取字符 用 法: int getc(FILE *stream);//read the next character from stream and return it as an unsigned char cast to a int ,or EOF on end of file or error. 注意: 此函数被ISO C声明为一个宏,所以在用时不能将其做为函数指针传(有一些编译器将其以函数形式也给另说)。它的原型如下 #define getc(_stream) (--(_stream)->_cnt >= 0?0xff & *(_stream)->_ptr++ : _filbuf(_stream)) 要看懂上面的声明,标记一下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 用法补充: 在C语言中,用函数getc(fgetc)从文件读取字符。getc、fgetc用法相同。 getc的调用形式:ch=getc(fp);此处的fp是文件指针;函数功能是从文件指针指向的文件读入一个字符,并把它作为函数值返回给字符型变量ch。 一个比较详细的程序例: 把一个已存在磁盘上的file_a.dat文本文件中的内容,原样输出到屏幕上 程序执行步骤: ①打开文件 ②从指定文件中读入一个字符 ③判断读入的是否是文件结束标志,若是,结束循环,执行步骤⑦。 ④把刚从文件中读入的字符输出到终端屏幕。 ⑤从文件中再读入一个字符。 ⑥重复步骤③至⑤。 ⑦正确关闭文件。 #include<stdio.h> #include<stdlib.h> void main() { FILE *fp; char ch; if((fp=fopen("D:\\\\file_a.dat","w"))==NULL) { printf("Cannot open this file!\"); exit(0); } ch=getchar(); for(;ch!='@';)/*创建文件并由用户输入字符,以@为输入结束标志*/ { fputc(ch,fp); ch=getchar(); } fclose(fp); if((fp=fopen("D:\\\\file_a.dat","r"))==NULL) { printf("Cannot open this file!\"); exit(0); } ch=fgetc(fp); for(;ch!=EOF;) { putchar(ch); ch=fgetc(fp); } fclose(fp); } 程序例: #include <stdio.h> int main(void) { char ch; printf("Input a character:"); /* read a character from the standard input stream */ ch = getc(stdin); printf("The character input was: '%c'\", ch); return 0; } |
随便看 |
百科全书收录4421916条中文百科知识,基本涵盖了大多数领域的百科知识,是一部内容开放、自由的电子版百科全书。