Okay, I'm sure there's something I'm missing here, but I have no idea what it is and I'm hoping someone could help me figure it out.
I'm reading in input from the command line and was writing a function that uses fgetc() to do so. However, a seemingly superficial change in the function causes it to behave completely differently.
This is the main() function:
while(1)
{
char* cmd = malloc(sizeof(char) * 80);
printf("Enter command: ");
read_flush(cmd, 80);
printf("%s\n", cmd);
free(cmd);
}
And this is one of the versions of read_flush():
int read_flush(char* buffer, int count)
{
int i, c;
for(i = 0; i < count; i++)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
}
return i;
}
This one works fine. You type in input and it will spit it back out. However, this next version causes main to just print "Enter command:" over and over without giving the user a chance to enter input.
int read_flush(char* buffer, int count)
{
int i, c;
while(i < count)
{
c = fgetc(stdin);
if(c == '\n' || c == EOF)
return i;
buffer[i] = (char)c;
i++;
}
return i;
}
What subtlety with fgetc() am I missing here?