How to write a program to compare character and line

Asked By 10 points N/A Posted on -
qa-featured

I am trying to learn the language C.

Here is one thing I want to know.

What are the program codes to compare and count character and line of a text file?

Please send your valuable opinions.

SHARE
Best Answer by Niley Samilene
Best Answer
Best Answer
Answered By 0 points N/A #145532

How to write a program to compare character and line

qa-featured

Hello Levi Jeensen ,

Comparing and counting character and line of a text file

The program codes are below

#include<stdio.h>
#include<string.h>

int main()
{
    FILE *ptr_file;
    char buf[200];
    char key[] = "test";
    int wordcount = 0;

    ptr_file = fopen("input.txt","r");

    while (fgets(buf,200, ptr_file)!=NULL)
    {
        if((strstr(buf,key)) !=NULL){
            wordcount++;
        }
    }
    fclose(ptr_file);
    printf("%d",wordcount);
}

Thanks.

Answered By 0 points N/A #196517

How to write a program to compare character and line

qa-featured

Hello,

Find the solution below.

#include <stdio.h>

#include <string.h>

#include < stdlib.h>

void main()

{

     FILE *fp;

     int c , nc=0, lines=0;

     fp = fopen( "Input.txt", "r" );    // Open a txt file from which you have to read lines and char

     if ( fp == NULL )

     {

           return;  // in case file has nothing return back main program

     }

     c = getc( fp ) ;            

     while (  c != EOF ) //Loop until you get End of file

     {

           if ( c  ==  ‘n’  )   //check for new line

                lines++ // increase the lines if newline character has found

          nc++ ; // increase character count

          c = getc ( fp ); //read a character

     }

     fclose( fp ); // Close the file

     printf(“There are %d characters n”, nc); 

     printf(“There are %d lines n”, lines );

}

Related Questions