Beginner needs help with character counter

0 Brian Dormisch · November 5, 2014
Hi everyone, first post here. I was trying to make a character counter that reads from a text file but if the file has new lines, the program does not count the right way.

Can someone help me? What am I missing?


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE * fPointer;
    fPointer = fopen("archivo.txt", "r");
    int i = 0;
    char array[100] = "";

    while(!feof(fPointer)){

        fgets(array, 100, fPointer);
        puts(array);

        do{
            i++;

    }while(array != NULL);

    }

    fclose(fPointer);

    printf("\nThe file has %d characters.\n", i);

    return 0;
}

Post a Reply

Replies

Oldest  Newest  Rating
0 Brian Dormisch · November 6, 2014
I think I wasn's explaining myself the right way, so I took some screenshots of what happens when I run the program with and without new lines.

This is without new lines:

http://i.imgur.com/1FvSIRR.png

This is with new lines:

http://i.imgur.com/31uTVni.png

And this is the code right now:


#include <stdio.h>
#include <stdlib.h>

int main()
{
    FILE * fPointer;
    fPointer = fopen("archivo.txt", "r");
    int i;
    char array[100] = "";


    while(!feof(fPointer)){


        fgets(array, 100, fPointer);

        puts(array);

        for(i=0; i<100; i++){
            if(array == NULL){
                break;
            }
        }
    }

    fclose(fPointer);

    printf("\nThe file has %d characters.", i);

    return 0;
}


I dont know why it repeats the last line at the end and only counts the characters of that final line. Any ideas?
Sorry in advance, I'm just getting into programming.
0 Brian Dormisch · November 5, 2014
Thanks. I will try with fseek(1) and see what happens. i'm not too sure how to use it though.
  • 1

C

106,929 followers
About

One of the most popular languages of all time.

Links
Moderators
Bucky Roberts Administrator