Write a program to prompt a user for a file name. Count: ? the number of charact
ID: 3655727 • Letter: W
Question
Write a program to prompt a user for a file name. Count: ? the number of characters in the file (letters or numbers) ? the number of words in the file ? the number of lines in the file Here is what i have so far. I cant get the output to work correctly i just get straight 0's. #include #includeint main() { FILE *fileobject; char fname[128]; int c,nc,nl,nw; nc = 0, nl = 0, nw = 0; printf("Enter filename: "); gets(fname); fileobject=fopen(fname, "r"); while ( (c = getc(fileobject)) != EOF ) { nc++; if (c == ' ') nl++; if (c == ' ') nw++; c = getc(fileobject); } printf("Number of characters = %d ", nc); printf("Number of lines = %d ", nl); printf("Number of words = %d ", nw); fclose(fileobject); system("PAUSE"); return 0; }Explanation / Answer
MY CODE :
#include <stdio.h>
#include <ctype.h>
int main (void) {
FILE* fin;
char filename[64];
int charcount = 0;
int wordcount = 0;
int linecount = 0;
char c;
char word[64];
char line[256];
printf("Enter the input file name ");
scanf("%s", filename);
if ((fin = fopen(filename, "r")) == NULL) { //opens the input file and
printf("Error opening input file "); //ends the program if
return 1; //the file cannot be opened
}
while (!feof(fin)) { //this block of code counts the number
c = fgetc(fin); //of alphanumeric characters in the file
if (isalnum(c)) {
charcount++;
}
}
rewind(fin); //returns to the beginning of the file
while (!feof(fin)) { //this block of code counts the number
fscanf(fin, "%s ", word); //of words in the file
wordcount++;
}
rewind(fin); //returns to the beginning of the file
while (!feof(fin)) { //this block of code counts the number
fgets(line, 256, fin); //of lines in the file
linecount++;
}
printf("Number of characters: %d "
"Number of words: %d "
"Number of lines: %d ", charcount, wordcount, linecount);
fclose(fin); //closes the input file
return 0;
}
-------End C Code------------
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.