Reputation: 9
#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?
Upvotes: 0
Views: 1599
Reputation: 134356
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 typeint
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()
andgetchar()
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.
Upvotes: 4