Write a file program to merge the content of source1.txt file and
source2.txt file to destination.txt file and display the fallowing from
the destination file.
• Count number of lines
• Count number of words
• Count the frequency of occurrence of the words
source1.txt
Hello Welcome to KSRCT
Hello Welcome to KSRCE
source2.txt
Hello Welcome to KSRIET
Hello Welcome to KSRCAS
Destination.txt
Hello Welcome to KSRCT
Hello Welcome to KSRCE
Hello Welcome to KSRIET
Hello Welcome to KSRCAS
Output display after reading from destination.txt file
Number of lines : 04
Number of words: 16
Frequency of words
Hello appears 4 times
Welcome appears 4 times
to appears 4 times
KSRCT, KSRCE, KSRIET and KSRCAS appears 1 times
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(){
char FILE_NAME[]="destination.txt";
int numberLines=0;
int numberWords=0;
char word[100][100];
int frequencies[100];
int i,j,counter;
FILE *source1File = fopen("source1.txt", "r");
FILE *source2File = fopen("source2.txt", "r");
FILE *destinationFile = fopen(FILE_NAME, "w");
char letter;
// merge the content of source1.txt file and source2.txt file to destination.txt file
while ((letter = fgetc(source1File)) != EOF){
fputc(letter, destinationFile);
}
fputc('\n', destinationFile);
while ((letter = fgetc(source2File)) != EOF){
fputc(letter, destinationFile);
}
fclose(source1File);
fclose(source2File);
fclose(destinationFile);
//Output display after reading from destination.txt file
destinationFile = fopen(FILE_NAME, "r");
if(destinationFile==NULL)
{
printf("File does not exist or can not be opened.");
}
else
{
while ((letter=getc(destinationFile)) != EOF) {
//Count number of lines
if (letter == '\n') { ++numberLines; }
//Count number of words
if (letter == ' ' || letter == '\n') { ++numberWords; }
}
if (numberWords > 0) {
++numberLines;
++numberWords;
}
//display the fallowing from the destination file.
//Number of lines
printf("Number of lines: %0d\n",numberLines);
//Number of words
printf("Number of words: %0d\n",numberWords);
//Frequency of words
printf("Frequency of words\n");
//Count the frequency of occurrence of the words
//Hello appears 4 times
//Welcome appears 4 times
//to appears 4 times
//KSRCT, KSRCE, KSRIET and KSRCAS appears 1 times
fclose(destinationFile);
destinationFile = fopen(FILE_NAME, "r");
numberWords=0;
while (fscanf(destinationFile, "%s", word[numberWords]) != EOF){numberWords++;}
for(i=0; i<numberWords; i++){
counter = 1;
for(j=i+1; j<numberWords; j++){
// If duplicate element is found
if(strcmp(word[i],word[j])==0){
counter++;
frequencies[j] = 0;
}
}
if(frequencies[i] != 0)
{
frequencies[i] = counter;
}
}
for(i=0; i<numberWords; i++)
{
if(frequencies[i] != 0)
{
printf("%s appears %d times\n",word[i],frequencies[i]);
}
}
fclose(destinationFile);
}
getchar();
getchar();
return(0);
}
Comments
Leave a comment