Hi,
I'm posting this on the off chance someone here knows a bit about C. I am having trouble with a function I have written. It is meant to read from stdin upto a maxmum number of characters or until EOF is encountered. It reads upto max fine however I have to either enter EOF on a line of its own or enter it twice to get the function to stop reading.
e.g.
Input:
Hello,[EOF]
How are you?[EOF]
What the function reads (assuming maximum is 10):
Hello,\nHo\0
After entering EOF the function will happily continue to collect input from stdin until I enter EOF again. At which it stops immeadiately without me having to press enter.
I have examined the behavoiur of the cat program on linux. As soon as it encounters EOF it will output what it has already read.
I was wondering if anyone knew why this strange behaviour occurs and how it can be changed. I am guessing it has something to do with the buffering of input but don't know what. The code to my function is below:
Any suggestions would be appreciated:
Function
char read_input (char str, int max)
{
int counter;
for (counter = 0; counter < max - 1; counter++, str++)
{
char c;
c = getchar();
if (c == EOF)
break;
else
*str = c;
}
*str = '\0';
return str;
}