0

Here I am searching a string in text file and replacing it with new string. In this code it finds but the new word wrights at the end of the text file and not replacing. Plz. can anybody help me.....

#include<stdio.h>
#include<conio.h>
#include<string.h>

void main()
 {
   FILE *fp;
   int f=0,l,n=0;
   char *st, *st1, *st2;
   clrscr();

   printf("\n\nEnter string to search:");
   scanf("%s",st1);
   printf("Enter text to replace:");
   scanf("%s",st2);


  fp=fopen("c:\\folder/file.txt","a+");


  while(!feof(fp))
   {
	fscanf(fp,"%s",st);
	
         if(strcmpi(st,st1)==0)
	{
	 f=1;
	 n++;     /*Number of time the string repeats*/
	 }
   }

	  if(f==1)
	    fprintf(fp,"%s",st2);

	fclose(fp);
	getche();
 }

Edited by WaltP: Added CODE Tags -- please use them

4
Contributors
4
Replies
9
Views
6 Years
Discussion Span
Last Post by pyTony
0

Your code shouldn't work because you're trying to get user input and put it into uninitialized pointers. You could turn those into char arrays or use malloc to initalize those char pointers.

Also, using scanf is unsafe. Look into using fgets.

0

You could combine reading in and comparison so you save replacement instead of the searched one to memory record during the read. Then you do not need to move string arrays in memory, only allocate space for the array and write it out after scan and replace.

This topic has been dead for over six months. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.