In: Computer Science
Write a C program that can search for a string within a text file, replace it with another string and put results in a new file.
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
void main()
{
//variable declaration
FILE *fptr, *outputfp;
char ch;
int wrd=1,charctr=1;
char fname[20];
//open file
fptr=fopen("inputFile.txt","r");
outputfp = fopen("outputFile.txt", "w");
char str[100];
char newStr[100];
char searchStr[] = "how";
char replaceStr[] = "done";
if(fptr==NULL || outputfp==NULL)
{
printf(" File does not exist or can not be opened.");
}
else
{
ch=fgetc(fptr);
int i = 0;
char c;
while(ch!=EOF)
{
str[i++] = ch;
ch=fgetc(fptr);
}
str[i++] = '\0';
}
int i = 0, j = 0;
int flag = 0, start = 0;
while (str[i] != '\0')
{
if (str[i] == searchStr[j])
{
if (!flag)
start = i;
j++;
if (searchStr[j] == '\0')
break;
flag = 1;
}
else
flag = start = j = 0;
i++;
}
if (searchStr[j] == '\0' && flag)
{
for (i = 0; i < start; i++)
putc(str[i], outputfp);
for (j = 0; j < strlen(replaceStr); j++)
{
putc(replaceStr[j], outputfp);
i++;
}
for (j = start + strlen(searchStr); j < strlen(str);
j++)
{
putc(str[j], outputfp);
i++;
}
newStr[i] = '\0';
}
//close file
fclose(fptr);
fclose(outputfp);
}
INPUT:
inputFile.txt
Search for a string = "how"
Replace with a string = "done"
outputFile.txt