Write a C program that opens a user given text file and does the following: 1) c
ID: 3767425 • Letter: W
Question
Write a C program that opens a user given text file and does the following:
1) counts the number of characters in the file
2) counts the number of "lines" in a file (a "line" is any series of characters ending with a newline ' ')
3) counts the number of words in the file (any sequence of non-white-space characters)
Your program should output all three values in a "user-friendly" way. Run this with one text file. Turn in your source code, the printed text file and a printout of the output.
HINT:This will be easier if you open the file and read it character-by-character first. This will allow you to easily count the characters and newlines. THEN close the file, reopen it and read through it using fscanf. When you tell fscanf to get a string, it only gets the characters UP TO the first white-space character.
Explanation / Answer
#include<stdio.h>
#include<conio.h>
void main()
{
int noc=0,now=0,nol=0;
FILE *fw,*fr;
char fname[20],ch;
clrscr();
printf(" enter the source file name");
gets(fname);
fr=fopen(fname,"r");
if(fr==NULL)
{
printf(" error ");
exit(0);
}
ch=fgetc(fr);
while(ch!=EOF)
{
noc++;
if(ch==' ');
now++;
if(ch==' ')
{
nol++;
now++;
}
ch=fgetc(fr);
}
fclose(fr);
printf(" total no of character=%d",noc);
printf(" total no of words=%d",now);
printf(" total no of lines=%d",nol);
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.