tags:

views:

269

answers:

2

I'm trying to write some code that reads a file and ignores the line breaks (\n), so far I have:

c = fgetc(fp);
for(int loop = 0; c != EOF; loop++)
{
    if((c != '\n') && (c != '\\'))
    {
     buffer[loop] = c;
    }
    c = fgetc(fp);
}

but its just not seeming to ignore the '\n' bits (not sure about the '\')

And sorry for the layout of the code, the site doesn't appear to like my version of Opera :(

Edit: Thanks guys, I've beed coding for about 6 hours straight and completely overlooked the incrementing, which is why I thought the \n remained still.

I also didn't know about the \r, uning Linux but trying to make cross platform so this is helpful.

+5  A: 

Which operating system you are running this on? \n on Windows is two characters (\r\n) . If you only want to ignore newlines, the second condition is not needed.

But another problem is that you increment loop variable every time! You should increment 'loop' only when you add stuff to the buffer! Take 'loop++' away from for(..) and add it to buffer[loop++] = c;. Most likely you get random characters in the buffer in place of '\n':s, which can well be zeroes, for instance.

antti.huima
On Windows, a file opened in text mode (i.e. without the 'b' character in fopen's mode argument) will have \r\n sequences changed to \n by stdio.
Doug
+8  A: 

try this

while ( (c = fgetc(fp)) != EOF )
{
  if ( c != '\n' && c != '\r' )
  {
    buffer[loop++] = c;
  }
}
Anders K.