151k views
2 votes
Write a program in C which will open a text file named Story.txt. You can create the file using any text editor like notepad etc., and put random words. Make sure the text file is in the same directory as your c program. Next, you need to ask the user for the file name and open the file. Check whether the file is opened successfully or not. If no then continue asking for a correct file name. After the successful opening of the text file, count the number of words and characters (no spaces) in the file. Finally, print the result into the output. You need to create at least 2 user-defined functions.

User Sujithvm
by
3.0k points

1 Answer

2 votes

Answer:

See explaination

Step-by-step explanation:

#include <stdio.h>

#include <stdlib.h>

int main()

{

FILE * file_object;

char file_name[100];

char ch;

int characters=0, words=0;

printf("Enter source file name: ");

scanf("%s", file_name); //asking user to enter the file name

file_object = fopen(file_name, "r"); //open file in read mode

if (file_object == NULL)

{

printf("\\Unable to open file.file not exist\\"); //check if the file is present or not

}

while ((ch = fgetc(file_object)) != EOF) //read each character till the end of the file

ch == '\0') //if character is space or tab or new line or null character increment word count

words++;

else

characters++; //else increment character count this assures that there is no spaces count

printf("The file story.txt has the following Statistics:\\"); //finally print the final statistics

if (characters > 0)

{

printf("Words: %d\\", words+1); //for last word purpose just increment the count of words

printf("Characters (no spaces): %d\\", characters);

}

fclose(file_object); //close the file object

return 0;

}

User Magic Bullet Dave
by
3.5k points