Vimzy
Vimzy

Reputation: 1965

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?

Upvotes: 2

Views: 24310

Answers (4)

Sourav Ghosh
Sourav Ghosh

Reputation: 134286

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

Upvotes: 4

Aditya Divekar
Aditya Divekar

Reputation: 23

Yes it does. It will add '\n' at the end of the line if it encounters it. If you want to get rid of it, compare the array index and replace it as desired using the follows. (change the '\0' as per your need)

if (arrayname[index] == '\n')
    arrayname[index]='\0';

Upvotes: 0

Gopi
Gopi

Reputation: 19864

char a[100];
size_t n;

fgets(a, sizeof(a),stdin);

n = strlen(a);
if (n > 0 && a[n - 1] == '\n')
    a[n-1] = '\0';

You can check whether there is a newline character in the buffer as shown above and suppress it by replacing newline character with \0

Upvotes: 0

Iharob Al Asimi
Iharob Al Asimi

Reputation: 53006

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.

Upvotes: 1

Related Questions