Hugo Hugo - 1 year ago 89
C Question

fgets cannot read newline character

char c[500];
fgets(c, 500, fp);

if (c == "\n") {
customer.checkoutTime = 0;
customer.payment = 0;

I want to store two zero in these two var if fgets read a blank line. But it fail, never execute the if-block code . How should fgets read a blank line?

Answer Source

From the description of fgets function:

The C library function char *fgets(char *str, int n, FILE *stream) reads a line from the specified stream and stores it into the string pointed to by str. It stops when either (n-1) characters are read, the newline character is read, or the end-of-file is reached, whichever comes first.

Same from man fgets:

fgets() reads in at most one less than size characters from stream and stores them into the buffer pointed to by s. Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer. A terminating null byte ('\0') is stored after the last character in the buffer.


fgets stops reading if it encounters a \n (new line) character, that's why you'll never find that character in your buffer.

Apart from this, the code you posted:

if (c == "\n") {

is wrong on several levels. "\n" yields a pointer to a read-only string (char *), which will never be equal to c. Use strcmp to compare strings. For characters, use single quotes, and to compare the value(s) in c, you'll have to dereference it:

if (c[i] == '\n') // or *c == '\n'