user1888502
user1888502

Reputation: 373

I need to read new line characters in a file

Suppose a text file has hello\n stack overflow \n in a file, the output should be 2 since there are 2 \n sequences. Instead, I am getting one as the answer. What am I doing wrong? Here is my code:

int main()
{
    FILE                *fp = fopen("sample.txt", "r");    /* or use fopen to open a file */
    int                 c;              /* Nb. int (not char) for the EOF */
    unsigned long       newline_count = 1;

        /* count the newline characters */
    while ( (c=fgetc(fp)) != EOF ) {
        if ( c == '\n' )
            newline_count++;
        putchar(c);
    }

    printf("\n  %lu newline characters\n ", newline_count);
    return 0;
}

Upvotes: 4

Views: 5785

Answers (1)

BenjiWiebe
BenjiWiebe

Reputation: 2235

Try this:

int main()
{
    FILE                *fp = fopen("sample.txt", "r");    /* or use fopen to open a file */
    int                 c, lastchar = 0;              /* Nb. int (not char) for the EOF */
    unsigned long       newline_count = 0;

        /* count the newline characters */
    while ( (c=fgetc(fp)) != EOF ) {
        if ( c == 'n' && lastchar == '\\' )
            newline_count++;
        lastchar = c; /* save the current char, to compare to next round */
        putchar(c);
    }

    printf("\n  %lu newline characters\n ", newline_count);
    return 0;
}

Really, a literal \n is two characters (a string), not just one. So you cannot simply compare it as though it was a character.

EDIT Since \n is two characters, the \ and the n, we must remember the last character we read in, and check if the current character is an n and the previous character is a \. If both tests are true, that means we have located the sequence \n in the file.

Upvotes: 3

Related Questions