ccharconceptual

Getting inflated results when trying to find newline '\n' in a char array in C


First I opened a .txt file (less than 1kb btw) and stored the string data in a char array like this---

FILE *file = fopen("./tmp.txt","r+");

char CharArray[10000];
fread(CharArray, 1, 10000, file);

Then I made a simple function that counts the newline character '\n'.

int NewLineCounter (char array[]) {
    int count = 0;

    for (int i=0; array[i]!='\0'; ++i) {
        if (array[i]=='\n') {
            printf("Found a line change.\n");
            count++;
        } else {continue;}
    }
    return count;
}

And ran like this---

printf("\nThis many lines found: %d.", NewLineCounter(CharArray));

The results aren't matching with what I see in the windows NotePad. Though, I can confirm the results are close, so this should not be a coincidence.

I did try these conditional changes---

if (array[i]=='\n' && array[i]!='\r' && array[i]!='\0') {...rest is same...}

I think I don't understand the concept of how a txt files work or how "fread" works


Solution

  • fread returns a value: The number of objects read.
    You should use this instead of ending the loop at '\0'.

    Also, '\0' does not necessarily appear at the end of a file. Here is my corrected version of your function:

    int NewLineCounter(const char *array, size_t length) {
        int count = 0;
    
        for (size_t i = 0; i < length; ++i) {
            if (array[i] == '\n') {
                count++;
            }
        }
        return count;
    }
    

    And here is how I'd call it:

    FILE *file = fopen("./tmp.txt", "r");
    char CharArray[10000];
    
    size_t bytesRead = fread(CharArray, sizeof(char), sizeof(CharArray), file);
    fclose(file);
    
    printf("This many lines found: %d\n", NewLineCounter(CharArray, bytesRead));
    

    Edited to include Ted Lyngmo's correction.