Check if String Contains New Line character

17,435

Solution 1

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].

Solution 2

Yes fgets() does read the '\n' character if it's present, to remove it you can do this

char   buffer[SIZE_OF_BUFFER];
size_t length;

/* * we assume that file is a valid 'FILE *' instance */

length = sizeof(buffer);
if (fgets(buffer, length, file) != NULL)
{
    length = strlen(buffer);
    if (buffer[length - 1] == '\n')
        buffer[--length] = '\0';
}

what this does is check if '\n' is present at the end of the string, and then replace it by the nul terminator.

Share:
17,435
Vimzy
Author by

Vimzy

Updated on June 26, 2022

Comments

  • Vimzy
    Vimzy almost 2 years

    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?

  • Iharob Al Asimi
    Iharob Al Asimi about 9 years
    If I were to hire you in my company I wouldn't because of your coding style, not your skills, they're ok, of course I don't have a company yet.
  • Gopi
    Gopi about 9 years
    @iharob Please consider my skills because I normally use vim editor to do my coding and after writing all the code just I do = and % to indent my whole code... Please consider my skills :):)
  • Iharob Al Asimi
    Iharob Al Asimi about 9 years
    You shouldn't make your editor indent the code for you.
  • Gopi
    Gopi about 9 years
    @iharob Using the available tools when needed is an excellent skill :) :)
  • Iharob Al Asimi
    Iharob Al Asimi about 9 years
    Formatting your code with a tool means you don't really care how your code looks. And writing code without any formatting is a bad thing to do in my opinion, because it probably makes you write faster but errors will be harder to detect. Also, suppose you are working on a file with > 1000 LOC.
  • Jongware
    Jongware about 9 years
    Both separate cases are caught at once with the line if (buffer[strlen(buffer)-1] ..