Israel
Israel

Reputation: 1224

Using fgets to read from a file

A Small C question for you, appreciate your help:

A file's first line is:
"add A"
It has more lines beneath.

I'm reading the first line from the file using fgets:

char str [500];
fgets(str,sizeof(str),filePointer);

Since fgets stops at the newline char, I replace the unwanted newline char with '\0':

char *p;
if ((p = strchr(str, '\n')) != NULL)
  *p = '\0';

Now if I print str this way:

printf("DEBUG: str:=[%s]\n",str);

Why do I get a crappy output like this:

]EBUG: str:=[add A

and not:

DEBUG: str:=[add A]

??
Thanks!!

Upvotes: 2

Views: 361

Answers (1)

nmaier
nmaier

Reputation: 33192

Your file likely uses \r\n line-endings (aka. Windows line-endings) and you therefore left a trailing \r in.

Kill the \r as well and you should be done.

Upvotes: 3

Related Questions