Assignment 10 PPS
Problem 1: Write a C program to create a file and write contents, save and close the file.
sol.
#include<stdio.h>
#include<string.h>
int main(){
FILE*fp; //creating file pointer
char ch; //declaring input sources
char str[100];
fp=fopen("ADK.txt","w"); //opening file named ADK.txt in write mode
if (fp==NULL){
printf("file not found"); //if file does not found
return 0;
}
else{
printf("enter some content you want to add in your file:\n"); //enter new data in your file
while(strlen(gets(str))>0){
fputs(str,fp);
fputs("\n",fp);
}
printf("data written successfully");
}
fclose(fp);//closing file after successful add of data into the file
}
Problem 2: Write a C program to read file contents and display on console.
sol.
#include<stdio.h>
#include<string.h>
int main(){
FILE*fp;
char ch;
fp=fopen("ADK.txt","r"); //opening file to read the content
if (fp==NULL){
printf("FILE NOT FOUND"); //if file does not exist
return 0;
}
else{
printf("content found in file:\n");
while(1){
ch=fgetc(fp);
if(EOF==ch){
break;
}
else{
printf("%c",ch); //displaying the content of file
}
}
}
fclose(fp); //closing the file after successful reading task
}
Problem 3: Write a C program to append content to a file..
sol.
#include<stdio.h>
#include<string.h>
int main(){
FILE*fp; //creating file pointer
char ch; //declaring input sources
char str[100];
fp=fopen("ADK.txt","a"); //opening file named ADK.txt in append mode
if (fp==NULL){
printf("file not found"); //if file does not exist
return 0;
}
else{
printf("enter some content you want to add in your file:\n"); //enter new data in your file
while(strlen(gets(str))>0){
fputs(str,fp);
fputs("\n",fp);
}
printf("data appendation is succesful");
}
fclose(fp); //closing file after successful append of data into file
fp=fopen("ADK.txt","r"); //opening file to read the content
if (fp==NULL){
printf("FILE NOT FOUND"); //if file does not exist
return 0;
}
else{
printf("\n\ncontent found in file:\n");
while(1){
ch=fgetc(fp);
if(EOF==ch){
break;
}
else{
printf("%c",ch); //displaying the content of file
}
}
}
fclose(fp); //closing the file after successful reading task
}
Problem 4: Write a C program to copy contents from one file to another file.
sol.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE*fptr1,*fptr2;
char c;
fptr1=fopen("ADK.txt","r");
if (fptr1==NULL){
printf("file does not found \n");
return 0;
}
fptr2=fopen("DK.txt","w");
if (fptr2==NULL){
printf("file does not exist");
return 0;
}
else{
while(1){
c=fgetc(fptr1);
if(c==EOF)
break;
fputc(c,fptr2);
}
}
fclose(fptr1);
fclose(fptr2);
}
Problem 5: Write a C program to compare the contents of two files and determine whether they are same or not.
sol.
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
int compareFiles(FILE *file1, FILE *file2){
char ch1 = getc(file1);
char ch2 = getc(file2);
int error = 0, pos = 0, line = 1;
while (ch1 != EOF && ch2 != EOF){
pos++;
if (ch1 == '\n' && ch2 == '\n'){
line++;
pos = 0;
}
if (ch1 != ch2){
error++;
printf("Line Number : %d \tError"" Position : %d ", line,pos);
}
ch1 = getc(file1);
ch2 = getc(file2);
}
printf("Total Errors : %d\t", error);
}
int main(){
FILE *file1 = fopen("ADK.txt", "r");
FILE *file2 = fopen("DK.txt", "r");
if (file1 == NULL || file2 == NULL){
printf("Error : Files do not exist");
exit(0);
}
compareFiles(file1, file2);
fclose(file1);
fclose(file2);
return 0;
}
Problem 6: Write a C program to count characters, words and lines in a text file.
sol.
#include<stdio.h>
#include<stdlib.h>
int main(){
FILE*fp;
char ch;
int nol=0,now=0,noc=0;
fp=fopen("ADK.txt","r");
while(1){
ch=fgetc(fp);
if(ch==EOF){
break;
}else{
noc++ ;
}
if (ch=='\n'){
nol++ ;
}
if (ch == ' '||ch== '\t'||ch =='\n'||ch=='\0'){
now++ ;
}
}
fclose(fp);
printf("number of characters:%d\n",noc);
printf("number of words:%d\n",now);
printf("number of lines:%d\n",nol);
}
Problem 7: Write a C program to find and replace a word in a text file.
sol.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
// Function declaration
void replaceAll(char *str, const char *oldWord, const char *newWord);
int main(){
// File pointer to hold reference of input file
FILE * fPtr;
FILE * fTemp;
char path[100];
char buffer[BUFFER_SIZE];
char oldWord[100], newWord[100];
printf("Enter path of source file: ");
scanf("%s", path);
printf("Enter word to replace: ");
scanf("%s", oldWord);
printf("Replace with: ");
scanf("%s", newWord);
// Open all required files
fPtr = fopen(path, "r");
fTemp = fopen("replace.tmp", "w");
// fopen() return NULL if unable to open file in given mode
if (fPtr == NULL || fTemp == NULL)
{
// Unable to open file hence exit
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read/write privilege.\n");
exit(EXIT_SUCCESS);
}
while ((fgets(buffer, BUFFER_SIZE, fPtr)) != NULL)
{
// Replace all occurrence of word from current line
replaceAll(buffer, oldWord, newWord);
// After replacing write it to temp file.
fputs(buffer, fTemp);
}
// Close all files to release resource
fclose(fPtr);
fclose(fTemp);
remove(path); // Delete original source file
rename("replace.tmp", path); // Rename temp file as original file
printf("\nSuccessfully replaced all occurrences of '%s' with '%s'.", oldWord, newWord);
return 0;
}
// Replace all occurrences of a given a word in string
void replaceAll(char *str, const char *oldWord, const char *newWord) {
char *pos, temp[BUFFER_SIZE];
int index = 0;
int owlen;
owlen = strlen(oldWord);
// Fix: If oldWord and newWord are same it goes to infinite loop
if (!strcmp(oldWord, newWord)) {
return;
}
//Repeat till all occurrences are replaced
while ((pos = strstr(str, oldWord)) != NULL) {
strcpy(temp, str); // Backup current line
index = pos - str; // Index of current found word
str[index] = '\0'; // Terminate str after word found index
strcat(str, newWord); // Concatenate str with new word
// Concatenate str with remaining words after
strcat(str, temp + index + owlen);
}
}
Problem 8: Write a C program to convert uppercase to lowercase character and vice versa in a text file.
sol.
#include<ctype.h>
#include <stdio.h>
#include <stdlib.h>
//function declartion
void toggleCase(FILE *fptr, const char *path);
int main() {
// File pointer to hold reference of input file
FILE *fPtr;
char path[100];
printf("Enter path of source file: ");
scanf("%s", path);
fPtr = fopen(path, "r");
// fopen() return NULL if unable to open file in given mode.
if (fPtr == NULL) {
// Unable to open file hence exit
printf("\nUnable to open file.\n");
printf("Please check whether file exists and you have read privilege.\n");
exit(EXIT_FAILURE);
}
toggleCase(fPtr, path);
printf("\nSuccessfully converted characters in file from uppercase to lowercase and vice versa.\n");
return 0;
}
//function defination
void toggleCase(FILE *fptr, const char *path) {
FILE *dest;
char ch;
dest = fopen("toggle.tmp", "w");// Temporary file to store result
//If unable to create temporary file
if (dest == NULL) {
printf("Unable to toggle case.");
fclose(fptr);
exit(EXIT_FAILURE);
}
//Repeat till end of file.
while ( (ch = fgetc(fptr)) != EOF) {
if (isupper(ch))
ch = tolower(ch);
else if (islower(ch))
ch = toupper(ch);
fputc(ch, dest); // Print toggled character to destination file.
}
//Close all files to release resource
fclose(fptr);
fclose(dest);
remove(path); //Delete original source file
//Rename temporary file as original file
rename("toggle.tmp", path);
}
Problem 9: Write a C program to check whether a given word exists in a file or not. If yes then find the number of times it occurs.
sol.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define BUFFER_SIZE 1000
//Function declarations
int countOccurrences(FILE *fptr, const char *word);
int main() {
FILE *fptr;
char path[100];
char word[50];
int wCount;
printf("Enter file path: "); // Input file path
scanf("%s", path);
printf("Enter word to search in file: "); // Input word to search in file
scanf("%s", word);
fptr = fopen(path, "r"); // Try to open file
// Exit if file not opened successfully
if (fptr == NULL) {
printf("Unable to open file.\n");
printf("Please check you have read/write previleges.\n");
exit(EXIT_FAILURE);
}
// Call function to count all occurrence of word
wCount = countOccurrences(fptr, word);
printf("'%s' is found %d times in file.", word, wCount);
fclose(fptr); // Close file
return 0;
}
//function defination
int countOccurrences(FILE *fptr, const char *word) {
char str[BUFFER_SIZE];
char *pos;
int index, count;
count = 0;
// Read line from file till end of file.
while ((fgets(str, BUFFER_SIZE, fptr)) != NULL) {
index = 0;
// Find next occurrence of word in str
while ((pos = strstr(str + index, word)) != NULL)
{
// Index of word in str is
// Memory address of pos - memory
// address of str.
index = (pos - str) + 1;
count++;
}
}
return count;
}
Problem 10: Write a C program to merge two files to a third file.
sol.
#include <stdio.h>
#include <stdlib.h>
int main() {
FILE *sourceFile1;
FILE *sourceFile2;
FILE *destFile;
char sourcePath1[100];
char sourcePath2[100];
char destPath[100];
char ch;
//Input path of files to merge to third file
printf("Enter first source file path: ");
scanf("%s", sourcePath1);
printf("Enter second source file path: ");
scanf("%s", sourcePath2);
printf("Enter destination file path: ");
scanf("%s", destPath);
sourceFile1 = fopen(sourcePath1, "r");
sourceFile2 = fopen(sourcePath2, "r");
destFile = fopen(destPath, "w");
//fopen() return NULL if unable to open file in given mode.
if (sourceFile1 == NULL || sourceFile2 == NULL || destFile == NULL) {
//Unable to open file hence exit
printf("\nUnable to open file.\n");
printf("Please check if file exists and you have read/write privilege.\n");
exit(EXIT_FAILURE);
}
while ((ch = fgetc(sourceFile1)) != EOF) // Copy contents of first file to destination
fputc(ch, destFile);
while ((ch = fgetc(sourceFile2)) != EOF) // Copy contents of second file to destination
fputc(ch, destFile);
printf("\nFiles merged successfully to '%s'.\n", destPath);
// Close files to release resources
fclose(sourceFile1);
fclose(sourceFile2);
fclose(destFile);
return 0;
}
0 comments:
Post a Comment