0% found this document useful (0 votes)
197 views2 pages

System Software Gtu

The document describes a C program that counts the number of characters, words, lines, and whitespace in a given input file. The program opens the file, initializes counting variables, and uses a while loop with fgetc() to iterate through the file character by character, incrementing the appropriate counter based on whether the character is a letter, space, newline, etc. It then prints the final counter values and closes the file. The output shows the counts for an input file called ss2.txt.

Uploaded by

Hot Tea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
197 views2 pages

System Software Gtu

The document describes a C program that counts the number of characters, words, lines, and whitespace in a given input file. The program opens the file, initializes counting variables, and uses a while loop with fgetc() to iterate through the file character by character, incrementing the appropriate counter based on whether the character is a letter, space, newline, etc. It then prints the final counter values and closes the file. The output shows the counts for an input file called ss2.txt.

Uploaded by

Hot Tea
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 2

System Software (3160715) 190160107096

Practical : 1
AIM : Write a C Program to count number of Characters, Words, lines
and Whitespace from the given input file.
Program :
#include <stdio.h>
#include <stdlib.h>

int main()
{
FILE * file;

char ch;
int characters, words, lines, whitespace;

file = fopen("ss2.txt", "r");

if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");

exit(EXIT_FAILURE);
}

characters = words = lines = whitespace = 0;


while ((ch = fgetc(file)) != EOF)
{
if (ch != ' ' && ch != '\n')
characters++;

if (ch == '\n' || ch == '\0')


lines++;

if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')


words++;

if (ch == ' ')


whitespace++;
}

if (characters > 0)
{
lines++;
}

1|Page
Practical 1
System Software (3160715) 190160107096

printf("\n");
printf("Total characters = %d\n", characters);
printf("Total words = %d\n", words);
printf("Total lines = %d\n", lines);
printf("Total whitespace = %d\n", whitespace);

fclose(file);

return 0;
}

ss2.txt

Output :

2|Page
Practical 1

You might also like