0

I'm trying to validate lines in a file with actual content in them, and exiting on cases where there are two empty lines in a row. Can this be done? This code results in fgetc() not catching the double carriage returns/new lines.

Code is a snippet from a C89 project, so declarations are made above snippet.

if ((file = fopen(fileName,"r")) == NULL)
{
    free(fileName);
    exit(1);
}

while (c != EOF)
{
    cOld = c;
    c = fgetc(file);

    /* count lines */
    if(c == '\n'){
        newLine++;
    }

    /* test for two carriage returns in a row */
    if(c == '\n' && cOld == '\n'){
        printf("ERROR: Invalid File\n");
        free(fileName);
        exit(1);
    }

}
user2470057
  • 529
  • 4
  • 17

1 Answers1

2

It seems that your are running your program on windows. In windows, end of line is represented by '\r\n'.

So when you check for c and cOld, they will not hold '\n' simultaneously.

Text files created on DOS/Windows machines have different line endings than files created on Unix/Linux. DOS uses carriage return and line feed ("\r\n") as a line ending, which Unix uses just line feed ("\n"). You need to be careful about transferring files between Windows machines and Unix machines to make sure the line endings are translated properly.

Please follow this link for more details: http://www.cs.toronto.edu/~krueger/csc209h/tut/line-endings.html

niyasc
  • 4,440
  • 1
  • 23
  • 50
  • ...but the file I'm testing was written in windows... so yeah, I think that's the issue. I'll do some testing based on that. It was confusing because everything I've read says that all OSes can handle '\n' as a new line. – user2470057 Mar 13 '15 at 09:23
  • This solution worked. I didn't need to follow any links, I just changed the file to have Unix line endings. Things worked out well. Thanks. – user2470057 Mar 13 '15 at 09:25
  • If the program is run on Windows (or DOS), and the file is opened in text mode, the stdio library will typically convert the two-byte line endings into a single `\n`. The problem occurs when Windows files are transfered to a non-Windows system without translation. – Nisse Engström Mar 13 '15 at 10:14