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();
 }

Do you know what the term append means? fp=fopen("c:\\folder/file.txt","a+");

Member Avatar for Mouche

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.

Thanks a lot....

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.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.