Write a C program that will process one or more files and print out various stat
ID: 3707027 • Letter: W
Question
Write a C program that will process one or more files and print out various statistics for these files. Thefile names should be provided via command-line arguments or the program will simply use stdio streamto get input (if there are no command-line arguments).If the user does not provide any command line arguments, the input should be read from the stdiostream instead of a standard file. If the user provides one or more command-line arguments, the pro-gram should process files with the names provided by command-line arguments one by one, and printout statistics for each file separately. If more files are processed, summary statistics should also beprinted out.The program should report the following statistics about each file (also summary statistics if multiplefiles are processed):i) Number of characters in the file.ii) Number of lines in the file (i.e. number of newline characters).iii) Number of words in the file. A word is a sequence of any characters except for the space,newlineor tabulator characters not separated by these characters. Therefore, in a string "This isthefirst line This his the 2nd"we wouldhave 9 words ( and arethe specialcharacters).The program will be similar to the wccommand provided in Linux(test it to get an idea). I’d suggest touse the functions defined in ctype.h. For example, isspaceis a good function to identify white spaceand distinguish it from the rest (other characters form words)
Explanation / Answer
#include <stdio.h>
int main(int argc, char** argv)
{
printf("You have entered %d number of arguments:",argc);
FILE *fp;
// char filename[100];
char ch;
int linecount, wordcount, charcount,i;
//argv[0] is the name of the program in the command line
for (i = 1; i < argc; ++i)
{
// Initialize counter variables
linecount = 0;
wordcount = 0;
charcount = 0;
// argv[i] is the name of the file from command line
// Open file in read-only mode
fp = fopen(argv[i],"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 != ' ')
{
++charcount;
}
// Increment word count if new line or space character
if (ch == ' ' || ch == ' ')
{
++wordcount;
}
// Increment line count if new line character
if (ch == ' ')
{
++linecount;
}
}
if (charcount > 0) {
++linecount;
++wordcount;
}
}
else
{
printf("Failed to open the file ");
}
printf("Lines : %d ", linecount);
printf("Words : %d ", wordcount);
printf("Characters : %d ", charcount);
}
return(0);
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.