Search code examples
coverflowfgets

C fgets - simple way to catch overflow?


Very simple example - hoping for a simple solution:

char x[7];
if(fgets(x,5,stdin))
    printf("y");
else
    printf("n");

I can't seem to get it to print "n" when I input more than the byte limit - is there any simple way I could enforce it or catch when it's surpassed?

As a side question, what example inputs would actually cause an "n" in the above snippet? I'm not really seeing the point right now..

Cheers, B


Solution

  • fgets returns NULL only if it failed to read anything, which usually means end of file.

    Since fgets reads a line, or as many characters of that line that fit in the buffer, you need to check if your variable x contains a newline character.