Specification: (16) (B) Write A C Program To Count The Number of Characters and Numbers of Lines in A File. Algorithm
Specification: (16) (B) Write A C Program To Count The Number of Characters and Numbers of Lines in A File. Algorithm
SPECIFICATION:
(16)(b) Write a c program to count the number of characters and numbers of lines in a file.
ALGORITHM:
Step1: Start
Step2: Declare file pointer fp, character ch, filename[20], and initialize noc=1, nol=0.
Step3: Read filename.
Step4:
Step 4.1: Open file fp in read mode.
Step 4.2: Condition (fp==NULL) prints data and stops if true, if false gets character from fp
and stores in ch.
Step 4.3: (ch!=EOF) is checked if true, noc is incremented
Step 4.3.1: (ch==\n) condition is checked if true nol is incremented.
Step 4.3.2: If the above step is true, then gets character from fp and stores in ch.
Step 4.3.3: Close the file fp.
Step5: Display number of characters and lines.
Step6: Stop
Flowchart:
Start
Read filename
Fp==NULL
True
False
Read first character in
fp and store in ch
Stop
False
Ch!=EOF
True
noc++
False
ch==\n
True
nol++
chfgetc fp
close file fp
Stop
PROGRAM
/*C program to count the number of characters and numbers of lines in a file.*/
Program name:
wk16b.c
/* Done By : C-Faculty
#include<stdio.h>
#include<curses.h>
int main()
{
int noc=0,nol=0;
FILE *fp;
char filename[25],ch;
clear();
printf(enter the file name);
gets(filename);
fp=fopen(filename,r);
if(fp==null)
{
printf(file cannot be opened);
return(0);
}
ch=fgetc(fp);
Department of Computer Science & Engg
Dated: 15/10/2013*/
while(ch!=EOF)
{
noc++;
if(ch=\n)
{
nol++;
}
ch=fgetc(fp);
}
fclose(fp);
printf(number of character are,%c,noc);
printf(number of lines are,%d,nol);
return(0);
}
PROCEDURE FOR EXECUTING THE PROGRAM:
Step 1: After typing the program, press ESC button+shift+: and then type wq(to save the program and
quit)
Step 2: Now compile the program by using the following command
cc wk16b.c lcurses
Step 3: Now go for running the program by using the command
./a.out
hi.txt
Sravan
Prasad
Radhika
Rajesh
number of character are:27
number of lines are: 4
ORIGINAL OUTPUT :
Output(1)
cat >> hi.txt // Already Content Existing File
Sravan
Prasad
Radhika
Rajesh
number of character are:27
number of lines are: 4
Output(2)
cat >> bii.txt // File Doesnt exists
file cannot be opened.
--xXx--