Search code examples
cstringfgetscharacter-arrays

Check if String Contains New Line character


I'm using fgets() with a buffer for a character array as I'm processing a file line by line. Will the buffer array contain the character, '\n' in its last position if it encounters a new line?

Does fgets() store '\n' in the buffer when a file starts a new line? If it doesn't, how can I check for them?


Solution

  • Yes. fgets() scans and stores the trailing \n in the destination buffer, if one is present in the source.

    Quoting the man page,

    Reading stops after an EOF or a newline. If a newline is read, it is stored into the buffer.

    So, to answer your query

    Check if String Contains New Line character [...] when a file starts a newline

    You can do, either

    • strchr() with \n to check if the input line contains \n anywhere
    • Check buffer[0] == '\n' for the starting byte only [file starts a new line case].