Hi,
I need to open a file, search for all occurrences of a substring and replace it with a given substring.
Any ideas about how to go about it, with the necessary functions, please.
Thanks,
Sashi
Another way for doing these with less memory consuming is to use a "backup file" just as follow:
#include<stdio.h>
#include<string.h>
void main()
{
FILE *fp,*fb; // fp : pointer for the original file(file1)
char buffer[25]; // fp : pointer for the backup file(file2)
char *string1 = "the searched string";
char *string2 = "string for replacement";
char c;
int size = 0;
if(( fp = fopen( "file1.txt", "r+" )) == NULL ) // opening the files
printf("ERROR:Unable to open \"file1\"\n"
if(( fb = fopen( "file12.txt", "w+" )) == NULL )
printf("ERROR:Unable to open or create \"file2\"\n"
size = strlen( string1 );
while(( fgets( buffer, size + 1, fp ) != NULL )) // search for string1 if found
{ // it is replace by string2 and copied to
if( !stricmp( buffer, string1 )) // the backup file
fputs( string2, fb );
else // otherwise,the original content of file1(the original file1)
fputs( buffer, fb ); // is copied to file12(the backup file1)
}
rewind( fb );
rewind( fp );
while(( c = getc(fb)) != EOF ) // Now,this is for outputing the file
{ // to the screen in order to see if the operation
putc( c, fp ); // has succeed.
putchar(c);
}
printf("\n"
fclose(fp); // closing the files
fclose(fb);
}
This site uses cookies to help personalise content, tailor your experience and to keep you logged in if you register.
By continuing to use this site, you are consenting to our use of cookies.