#include <stdio.h> 
#include <fcntl.h> 
Includes files necassary for the program to work. "stdio.h" for standard 
input/output functions such as printf(), scanf() etc. and "fcntl.h" for file 
handling functions such as fopen() 
int main() 
{ 
Declaration of function main(). 
 
char ch; 
int nol=0,not=0,nob=0,noc=0; 
Variables include number of lines, number of tabs, number of blanks and 
number of characters 
 
FILE *fp; 
Declaring a pointer variable for file handling use. 
char name[20]; 
Declaring a string to use for file name. 
printf("Enter File Name:"); 
Displaying a prompt for user saying "Enter File Name:" 
gets(name); 
Inputting file name in form of string 
fp=fopen(name,"r"); 
Opening a file based on filename in write mode (r) and issuing it to pointer 
fp 
 
if(fp==NULL) 
    { 
    printf("\nCannot open file\n"); 
    goto programend; 
} 
 If file cannot be opened (thus returning fp as NULL) display "Cannot open 
file" and goto end of program which is displayed after file usage. (exit 
function can be used here but that would make things complicated) 
 
while(1) 
    { 
    Using an infinite loop, it will keep repeating forever until we make it 
    break out of loop. 
    
    ch=fgetc(fp); 
    Character variable we defined earlier in the beginning of main function is 
    assigned the value of current character cursor is on (or under consideration in 
    other words). 
     
    if(ch==EOF) break; 
    If current character under consideration is End Of File (meaning file's end 
    has came), break out of infinite loop thus going to end of program. 
     
    noc++; 
    Passed above conditions, now value number of characters is increased by 1 
    if(ch==' ') nob++; 
    if current character is space/blank, value number of blanks is increased by 
    1 
    if(ch=='\n') nol++; 
    if current character is new line character, value number of lines is 
    increased by 1 
    if(ch=='\t') not++; 
    if current character is tab character, value number of tabs is increased by 
    1 
} 
 fclose(fp); 
Close opened file 
printf("\nChracters=%d \nBlanks=%d \nTabs=%d \nLines=%d \n", noc, nob, 
not, nol); 
Display our calculations 
 programend: 
The point of program end. if anywhere in the program it is said that goto 
programend; the program will jump here. 
 return (0); 
Beginners don't need to understand this, for advanced users main function 
returns nothing. 
} 
Main function closes here. 
DO NOT FORGET TO RATE THIS TUTORIAL. ITS EASY, JUST SCROLL DOWN AND YOU'LL SEE SCROLLING BOX
 |