Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,885 questions

51,811 answers

573 users

How to get the total number of lines in a text file in C

2 Answers

0 votes
#include <stdio.h> 
 
int get_total_number_of_lines(char filename[]) {
    FILE* fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Could not open file %s", filename);
        return -1;
    }
 
    int ch, number_of_lines = 0;
 
    do
    {
        ch = fgetc(fp);
        if (ch == '\n') {
            number_of_lines++;
        }
    } while (ch != EOF);
 
    fclose(fp);
 
    // last line doesn't end with a '\n'
    if (ch != '\n' && number_of_lines != 0) {
        number_of_lines++;
    }
 
    return number_of_lines;
}
 
int main(void)
{
    char filename[] = "d:\\data.txt";
 
    printf("number of lines = %d", get_total_number_of_lines(filename));
 
    return 0;
}
 
 
/*
run:
 
number of lines = 4
 
*/

 



answered Jul 6, 2024 by avibootz
edited Jul 6, 2024 by avibootz
0 votes
#include <stdio.h> 

int get_total_number_of_lines(char filename[]) {
    FILE* fp = fopen(filename, "r");
    if (fp == NULL) {
        printf("Could not open file %s", filename);
        return -1;
    }

    int ch, number_of_lines = 0;

    for (ch = getc(fp); ch != EOF; ch = getc(fp)) {
        if (ch == '\n') {
            number_of_lines++;
        }
    }

    fclose(fp);

    // last line doesn't end with a '\n'
    if (ch != '\n' && number_of_lines != 0) {
        number_of_lines++;
    }

    return number_of_lines;
}

int main(void)
{
    char filename[] = "d:\\data.txt";

    printf("number of lines = %d", get_total_number_of_lines(filename));

    return 0;
}


/*
run:

number of lines = 4

*/

 



answered Jul 6, 2024 by avibootz
edited Jul 6, 2024 by avibootz
...