How to count the number of characters in file with C

1 Answer

0 votes
#include <stdio.h>
#include <errno.h>

long count_characters(FILE* fp) {
    fseek(fp, -1L, 2); // move fp to last character of file 

    return ftell(fp) + 1; 
}

int main(void) {
    FILE* fp_read = NULL;

    if (fp_read = fopen("data.txt", "r")) {
        long total_chars = count_characters(fp_read);
        printf("%ld", total_chars);
    }
    else {
        perror("Error open files\n");
    }

    return 0;
}



/*
run:

21

*/

 



answered Mar 2, 2023 by avibootz

Related questions

1 answer 185 views
1 answer 122 views
1 answer 187 views
1 answer 182 views
1 answer 105 views
2 answers 216 views
...