0
#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?

  • 7
    `ch` **must** be defined as `int`. – pmg Jan 15 '16 at 17:02
  • 1
    2nd `fp=fopen("input.txt","w");` : `"w"` --> `"r"` – BLUEPIXY Jan 15 '16 at 17:03
  • same question? http://stackoverflow.com/questions/1782080/what-is-eof-in-the-c-programming-language – terence hill Jan 15 '16 at 17:04
  • 3
    `int main` not `void main`. – Kaz Jan 15 '16 at 17:15
  • 1
    I don't understand what this question is about. Please reformat the question in this way: *"The program is showing /behavior X/. I am puzzled, because I am expecting /behavior Y/."* In other words, what is or is not happening relative to your expectation? – Kaz Jan 15 '16 at 17:17
  • EOF is not a function. Question is meaningless. Don't use quote formatting for text that isn't quoted. – user207421 Jan 15 '16 at 18:24
  • @FUZxxl ch should be defined as int if you want your program to both compile and work – pm100 Jan 15 '16 at 18:25
  • I suspect the question really is 'why doesnt this program work'. pmg and BLUEPIXY have given answers – pm100 Jan 15 '16 at 18:26

1 Answers1

4

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.

Sourav Ghosh
  • 133,132
  • 16
  • 183
  • 261