How to write a program to compare character and line
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.
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.
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.
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 );
}