How does the EOF macro work with getchar?

岁酱吖の 提交于 2020-01-11 13:58:50

问题


#include<stdio.h>

int main(void) {
    FILE *fp;
    int ch;
    fp = fopen("input.txt", "w");
    printf("Enter data");
    while ((ch = getchar()) != EOF) {
        putc(ch, fp);
    }
    fclose(fp);
    fp = fopen("input.txt", "w");
    while ((ch = getc(fp)) != EOF) {
        printf("%c", ch);
    }
    fclose(fp);
}

How does the first while loop stop inputting from user? Since there is EOF present as a condition.

Or else do I need to use for loop?


回答1:


EOF is a value, not a function. It is essentially defined as a macro.

For reference, from C11, chapter §7.21.1, <stdio.h>

EOF
which expands to an integer constant expression, with type int and a negative value, that is returned by several functions to indicate end-of-file, that is, no more input from a stream;[...]

In case, getchar() fails, it will return a value which is defined as EOF.

Quoting from the manual page (emphasis mine)

fgetc(), getc() and getchar() return the character read as an unsigned char cast to an int or EOF on end of file or error.

EOF represents a value that may not fit into a char type. You must use int type for ch variable.

How does the first while loop stop inputting from user?

use CTRL+D on linux, and CTRL+Z on windows.



来源:https://stackoverflow.com/questions/34816138/how-does-the-eof-macro-work-with-getchar

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!