188k views
3 votes
Write a program using the standard library I/O functions (fopen, fread, fwrite, fclose, ferror, feof, and fflush) to read a text file and search it for a string (specified on the command line) in each line of an input file (whose name is also specified on the command line); if the string is found substitute another string (also specified on the command line) ONLY ONCE on the line.Write the output with the substitutions to the stdout, and write any errors to the stderr.

User Egil
by
8.2k points

1 Answer

4 votes

Answer:

See explaination

Step-by-step explanation:

#include <stdio.h>

#include <stdlib.h>

#include<string.h>

int main(int argc, char *argv[])

{

FILE *fr,*fr1,*fr3; /* declare the file pointer */

char filename[256];

char search[256];

char line[256];

int count=0;

char replace[256];

printf("Enter FileName: "); // ask for filename

scanf("%s",filename);

fr3 = fopen (filename, "r");

if(ferror(fr3)) //check for any error assosicated to file

{

fprintf(stderr, "Error in file"); // print error in stderr

printf("Error");

}

printf("Input file data is");

while(!feof(fr3)) // checking end of file condition

{ //printf("inside");

fgets(line,256,fr3) ;

printf("%s",line);

}

printf("\\Enter String to search: "); //ask for string to search

scanf("%s",search);

printf("Enter string with whom you want to replace: "); //ask for string with whom you want to replace one time

scanf("%s",replace);

fr = fopen (filename, "r"); // open first file in read mode

fr1 = fopen ("output.txt", "w"); //open second file in write mode

if(ferror(fr)) //check for any error assosicated to file

{

fprintf(stderr, "Error in file"); // print error in stderr

printf("Error");

}

while(!feof(fr)) // checking end of file condition

{ //printf("inside");

fgets(line,256,fr) ;

int r=stringCompare(line,search); // comparing every string and search string

// printf("%d",r);

if(r==1 && count==0)

{

fwrite(replace , 1 , sizeof(replace) , fr1 ); // writing string to file.

printf("%s\\",replace);

count++;

}

else{

printf("%s",line);

fwrite(line , 1 , sizeof(line) , fr1 );

}}

printf("\\");

fflush(fr1); // it will flush any unwanted string in stream buffer

fflush(fr);

fflush(fr3);

fclose(fr); //closing file after processing. It is important step

fclose(fr1);

fclose(fr3);

system("PAUSE");

return 0;

}

// Compare method which is comparing charaacter by character

int stringCompare(char str1[],char str2[]){

int i=0,flag=0;

while(str1[i]!='\0' && str2[i]!='\0'){

if(str1[i]!=str2[i]){

flag=1;

break;

}

i++;

}

if (flag==0 && (str1[i]=='\0' || str2[i]=='\0'))

return 1;

else

return 0;

}

User Searles
by
7.9k points