In: Computer Science
Write a C program that, given a file named Program_2.dat as input, determines and prints the following information:
Your program should assume that the input file, Program_2.dat, may contain any text whatsoever, and that text might be, or might not be, the excerpt from A Tale of Two Cities shown below.
Assume that the program will be tested using gcc (GCC) 8.2.0.
Sample Run # 1
When file Program_2.dat is present in the current working directory.
Program_2_jeffsolheim.c 14 FEB 2019 This program reads text from Program_2.dat and determines: 1. The number of characters in the file. 2. The number of uppercase letters in the file. 3. The number of lowercase letters in the file. 4. The number of words in the file. 5. The number of lines in the file. The file Program_2.dat contains: 631 characters 4 uppercase letters 471 lowercase letters 119 words 17 lines
Sample Run # 2
When file Program_2.dat is not present in the current working directory.
Program_2_jeffsolheim.c 14 FEB 2019 This program reads text from Program_2.dat and determines: 1. The number of characters in the file. 2. The number of uppercase letters in the file. 3. The number of lowercase letters in the file. 4. The number of words in the file. 5. The number of lines in the file. Error! Failed to open Program_2.dat!
Sample Input File
It was the best of times, it was the worst of times, it was the age of wisdom, it was the age of foolishness, it was the epoch of belief, it was the epoch of incredulity, it was the season of Light, it was the season of Darkness, it was the spring of hope, it was the winter of despair, we had everything before us, we had nothing before us, we were all going direct to Heaven, we were all going direct the other way-- in short, the period was so far like the present period, that some of its noisiest authorities insisted on its being received, for good or for evil, in the superlative degree of comparison only.
Here is the code in c for the above question:
#include <stdio.h> int main() { FILE *fp; char filename[100]; char ch; int linecount, wordcount, charcount; // Initialize counter variables linecount = 0; wordcount = 0; charcount = 0; // Prompt user to enter filename printf("Enter a filename :"); gets(filename); // Open file in read-only mode fp = fopen(filename,"r"); // If file opened successfully, then write the string to file if ( fp ) { //Repeat until End Of File character is reached. while ((ch=getc(fp)) != EOF) { // Increment character count if NOT new line or space if (ch != ' ' && ch != '\n') { ++charcount; } // Increment word count if new line or space character if (ch == ' ' || ch == '\n') { ++wordcount; } // Increment line count if new line character if (ch == '\n') { ++linecount; } } if (charcount > 0) { ++linecount; ++wordcount; } } else { printf("Failed to open the file\n"); } printf("Lines : %d \n", linecount); printf("Words : %d \n", wordcount); printf("Characters : %d \n", charcount); getchar(); return(0); }