0

I want to trim newline character from fgets output.

while(fgets(buff,1024,fp) ){

    printf("start%send",buff );

If there is a line "C is cool", in the file . Then the above code prints.

startC is cool
end 

But I want it to print like

 startC is coolend 

How to do that

tarun14110
  • 940
  • 5
  • 26
  • 57

2 Answers2

7

Clean approach

#include <string.h>

//...

buff [ strcspn(buff, "\r\n") ] = 0;

This will work safely for any flavour of line endings, even if there is none present, and even if the string is empty.

Weather Vane
  • 33,872
  • 7
  • 36
  • 56
2

You can set the last character to '\0' (null terminator). This is not a good approach because the file may not have always have a newline.

buff[strlen(buff) - 1] = '\0';

or loop over the char array end replace the '\n' with '\0'

int i;
for(i = 0; i < strlen(buff); i++)
{
    if(buff[i] == '\n')
    {
        buff[i] = '\0';
        break;
    }
}

or remove the '\n' at the end with strcspn():

buff[strcspn(buff, "\r\n")] = 0;
Jonathan Leffler
  • 730,956
  • 141
  • 904
  • 1,278
John G
  • 98
  • 5
  • The last line read from a file might not have a `newline`, in which case your first example is weak. The `newline` is not added by `fgets`, it is what was in the file. – Weather Vane Dec 31 '15 at 17:45
  • True, I only included it because it is an approach that would work for this question. I'll edit to clarify that it's not a good approach. – John G Dec 31 '15 at 17:48
  • If `strlen(buff)` is 0 this produces dangerous undefined behavior. – R.. GitHub STOP HELPING ICE Dec 31 '15 at 17:57
  • that wouldn't happen in this case because fgets would return a null pointer which would cause the while loop condition to fail – John G Dec 31 '15 at 18:05