本帖最后由 人造人 于 2017-6-4 19:42 编辑
这个问题和fgetc函数有关
这是 fgetc 函数的一部分,我找不到完整的^_^
- #define NOCCARGC /* no argument count passing */
- #include stdio.h
- #include clib.def
- /*
- ** Character-stream input of one character from fd.
- ** Entry: fd = File descriptor of pertinent file.
- ** Returns the next character on success, else EOF.
- */
- fgetc(fd) int fd; {
- int ch;
- char buff;
- if(Uread(&buff,fd,1)==EOF) {
- Useteof(fd);
- return(EOF);
-
- }
- ch=buff;
- switch(ch) {
- default: return (ch);
- case FILEOF: /* switch(Uchrpos[fd]) {
- default: --Uchrpos[fd];
- case 0:
- case BUFSIZE:
-
- } */
- Useteof(fd);
- return (EOF);
- case CR: return ('\n');
- case LF: /* NOTE: Uconin() maps LF -> CR */
-
- }
-
- }
- #asm
- _getc EQU _fgetc
- PUBLIC _getc
- #endasm
复制代码
调用 Uread 读一个字符到 buff
如果已经到文件末尾,用 Useteof设置 eof,返回eof
只有用Useteof设置过eof,用feof才能获取到
在程序中
- #include <stdio.h>
- int main(void)
- {
- FILE *fp = fopen("C:\\workspace\\test.dat", "r");
- char c;
- while (!feof(fp))
- {
- c = fgetc(fp);
- printf("%X/n", c);
- }
- return 0;
- }
复制代码
假设文件 C:\\workspace\\test.dat中只有1个字节
程序从main函数开始
首先打开文件
然后用feof判断文件,此时eof还没有被设置
然后调用fgetc 从test.dat中读1个字节,fgetc正常读取,返回test.dat中的那一个字节
然后输出
然后判断feof,因为上一次fgetc 正常读取,并没有设置eof,feof也就获取不到eof
然后执行fgetc ,这一次因为文件test.dat已经到末尾了,fgetc使用 Useteof设置 eof,返回eof
然后输出,这次printf输出的是eof
然后调用feof判断 ,因为fgetc 使用Useteof设置了 eof,所以while循环退出,
然后return 0;
弄明白这个问题的关键是,这个问题中有2个eof,一个是操作系统返回给库函数的eof,另一个是库函数返回给应用程序的eof