Read from a File

Write a program to print the number of characters and lines in a file. You should ignore the space, tab and newline characters for the character count

Create a file called input.txt in the same directory as this file and enter some lines of text or copy a paragraph of text. The filename should be input.txt

#include <stdio.h>

#include <stdlib.h>

int main() {

FILE *fp;

int line_count = 0, char_count = 0;

char c;

fp = fopen("input.txt", "r");

if (fp == NULL) {

printf("\nThe file cannot be opened in read mode\n");



c = fgetc(fp);

while ( c != EOF ) {

/* If the character read is a newline or tab or space */

if ( c == '\n' || c == '\t' || c == '\b' ) {

/* If it is a newline character increment the line count */

if ( c == '\n')


/* Read the next character from the file */

c = fgetc(fp);

/* Continue with the next iteration */



/* Since the character is not a newline, tab or space increment

the character count



c = fgetc(fp);


/* Since we are done processing the entire file we print the

the charcter count and the word count for the file


printf("\n The number of characters = %d\n", char_count);

printf("\n The number of lines = %d\n", line_count);

return 0;