In: Computer Science
Write a C program to find out the number of words in an input text file (in.txt). Also, make a copy of the input file.
Solve in C programming.
#include<stdio.h>
#include<stdlib.h>
int main(){
char ch,path[50],cpath[50];
FILE *file,*cfile;
int count=0;
//Enter the source path of the file
printf("Enter source file path: ");
scanf("%s", path);
file=fopen(path,"r");
if (file == NULL)
{
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read privilege.\n");
return 0;
}
//Gets each character till end of file is reached
while((ch = fgetc(file)) != EOF){
//Counts each word
if (ch == ' ' || ch == '\t' || ch == '\n' || ch == '\0')
count++;
}
printf("\nNumber of words given in the text file is : %d\n",count+1);
fclose(file);
//Give a file name to the copied file
printf("\nEnter the name of the new file :");
scanf("%s",cpath);
//if file not present, automatically file gets created
cfile=fopen(cpath,"w");
file=fopen(path,"r");
while ((ch = fgetc(file)) != EOF)
fputc(ch, cfile);
printf("\nCopy of file created\n");
//closing both files
fclose(file);
fclose(cfile);
return 0;
}
OUTPUT:
I have created a text fie named "in" in my dekstop. Then with the given code i have made a copy of "in" file into "copy_in" file