Write a program in C89 that takes in a TEXT FILE as input in via a command line
ID: 664901 • Letter: W
Question
Write a program in C89 that takes in a TEXT FILE as input in via a command line argument. The program should print to the screen the number of characters in that file, the number of words in that file (a word is any sequence of non-white-space characters), and the number of lines in that file.
Design the program to include encapsulating functionality and logical organization of functionality.
Additional: Output a bag of words of the words in the text file. Output this to bagofwords.txt. Look here for an understanding: https://en.wikipedia.org/wiki/Bag-of-words_model (Links to an external site.)
Standard Input/Output Example
./a.out sometextfile.txt
Number of Characters: 65
Number of Words: 18
Number of Lines: 3
Bag of Words Output File
John: 1
likes: 2
to: 3
watch: 4
movies: 5
also: 6
football: 7
games: 8
Mary: 9
too: 10
Explanation / Answer
comments added
#include<stdio.h>
#include<conio.h>
#include<string.h>
void main()
{
//variables declared
int number_of_characters=0,number_of_words=0,number_of_lines=0;
FILE *fw,*br;
char filename[20],character;
printf("PLease enter file name");
gets(filename); //reading filename
br=fopen(filename,"r");
if(br==NULL)
{
printf(" File cannot be opened");//when file not found
}
character=fgetc(br);
while(character!=EOF)//iterating text to get chars,words,lines
{
number_of_characters++;
if(character==' ');
number_of_words++;
if(character=='n')
{
number_of_lines++;
number_of_words++;
}
character=fgetc(br);
}
int i, j;
char myArray[128][128],duplicateArray[128][128];;
char eachline[128]; //required arrays declaring
for(i=0; i<128; i++)
for(j=0; j<128; j++)
myArray[i][j] = '';
for(i=0; i<128; i++)
eachline[i] = '';
if ( br != NULL )
{
i=0;
while ( fgets ( eachline, sizeof eachline, br ) != NULL ) //reading each line
{
strcpy(myArray[i], eachline);//copying to array
i++;
}
}
//printing final results
fclose(br);
printf(" total characters=%d",number_of_characters);
printf(" total words=%d",number_of_words);
printf(" total lines=%d",number_of_lines);
getcharacter();
int frequency=0,k=0,c;
//comparing all words
for (i = 0;i <= number_of_words;i++)
{
for (j = 0;j <= number_of_words;j++)
{
if (i == j)
{
strcpy(duplicateArray[k], myArray[i]);
k++;
frequency++;
break;
}
else
{
if (strcmp(duplicateArray[j], myArray[i]) != 0)
continue;
else
break;
}
}
}
for (i = 0;i < frequency;i++)
{
for (j = 0;j <= number_of_words;j++)
{
if (strcmp(duplicateArray[i], myArray[j]) == 0)
c++;
}
printf("%s -> %d times found ", duplicateArray[i], c); // final data printing
c = 0;
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.