Welcome, Guest. Please login or register.

Author Topic: More elegant way of removing/ignoring \n  (Read 2440 times)

Description:

0 Members and 1 Guest are viewing this topic.

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: More elegant way of removing/ignoring \n
« on: May 21, 2009, 03:17:32 PM »
Quote from: Marcb;455462
I'm putting together a small app that reads paths entered line by line in a text file.

I know the issue with reading a variable length line using Fgets and the newline character is as old as the hills but I was wondering if anyone has a more elegant way of dealing with the newline character than my method? :

Fgets(buf,sizeof(buf),*file);
buf[strlen(buf)-1]='\0';

It works but I always think it's too messy and that there must be a better way...

One way to handle it is to use sscanf:
Code: [Select]
#include <stdio.h>

int main(void)
{
  char tmp[80], buf[80];
  while (fgets(tmp, sizeof(tmp), stdin))
  {
    if (sscanf(tmp, &quot;%[^\r\n]&quot;, buf) != 1)
    {
      buf[0] = '\0';
    }
    printf(&quot;%s\n&quot;, buf);
  }
  return 0;
}
 

Offline Piru

  • \' union select name,pwd--
  • Hero Member
  • *****
  • Join Date: Aug 2002
  • Posts: 6946
    • Show all replies
    • http://www.iki.fi/sintonen/
Re: More elegant way of removing/ignoring \n
« Reply #1 on: May 21, 2009, 03:21:41 PM »
Quote from: MrZammler;455463
That's not bad, but to be complete you should also check for DOS line endings (\r\n) in case those files are edited in a Windows machine.

As far as I know all libc implementations on windoze do automagic \r\n -> \n translation when reading file opened in 'text' mode (that is no "b" is appended to the fopen mode. stdin/stdout/stderr are in this mode, too). Also, when writing to filehandle that is in 'text' mode single \n again is translated to \r\n.

Checking for \r doesn't hurt, however.