PSPC Lab-11
PSPC Lab-11
1. Write a program to print the number of lines and words in a given input file name.
Source Code:-
#include <stdio.h>
#include <stdbool.h>
bool isWhitespace(char c) {
return (c == ' ' || c == '\t' || c == '\n' || c == '\r');
}
int main() {
FILE *file;
int lineCount = 0;
int wordCount = 0;
char c;
bool inWord = false;
file = fopen("1.txt", "r");
if (file == NULL) {
printf("File not found or unable to open the file.\n");
return 1;
}
while ((c = fgetc(file)) != EOF) {
if (c == '\n') {
lineCount++;
}
if (isWhitespace(c)) {
inWord = false;
} else if (!inWord) {
inWord = true;
wordCount++;
}
}
fclose(file);
printf("The given file has %d lines and %d words.\n",lineCount, wordCount);
return 0;
}
#include <stdio.h>
int main() {
FILE *sourceFile, *destinationFile;
char c;
sourceFile = fopen("source.txt", "r");
if (sourceFile == NULL) {
printf("Source file not found or unable to open the file.\n");
return 1;
}
destinationFile = fopen("destination.txt", "w");
if (destinationFile == NULL) {
printf("Unable to create or open the destination file.\n");
fclose(sourceFile);
return 1;
}
while ((c = fgetc(sourceFile)) != EOF) {
fputc(c, destinationFile);
}
fclose(sourceFile);
fclose(destinationFile);
printf("Source File successfully copied to Destination File.\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE *sf, *df;
char ch;
sf=fopen("source3.txt","r");
if(sf==NULL){
printf("Error while opening the file.\n");
exit(1);
}
df=fopen("destination3.txt","a");
if(df==NULL){
fclose(sf);
printf("Error while opening the file.\n");
exit(1);
}
while((ch=fgetc(sf))!=EOF){
fputc(ch,df);
}
fclose(sf);
fclose(df);
printf("File appended successfully..\n");
return 0;
}
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
int main(){
FILE *file;
char word[20],line[100];
printf("Enter the word to search : ");
scanf("%s",word);
file=fopen("4.txt","r");
if(file==NULL){
printf("Error in opening the file.\n");
exit(1);
}
int lineNumber=0;
while(fgets(line,sizeof(line),file)!=NULL){
lineNumber++;
if(strstr(line,word)!=NULL){
printf("Word found at line %d : %s \n",lineNumber,line);
}
}
fclose(file);
return 0;
}