Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations gkittelson on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

File manipulation

Status
Not open for further replies.

malladisk

Programmer
Jun 14, 2001
69
US
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
 
open the file

copy the file into a buffer

use strstr to find the string.

use strncpy to copy the characters up til the found string into a new buffer

write the new buffer to a file

advance your pointer to the buffer n where n + return value of strstr

rinse and repeat

Matt
 
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 = &quot;the searched string&quot;;
char *string2 = &quot;string for replacement&quot;;
char c;
int size = 0;
if(( fp = fopen( &quot;file1.txt&quot;, &quot;r+&quot; )) == NULL ) // opening the files
printf(&quot;ERROR:Unable to open \&quot;file1\&quot;\n&quot;);
if(( fb = fopen( &quot;file12.txt&quot;, &quot;w+&quot; )) == NULL )
printf(&quot;ERROR:Unable to open or create \&quot;file2\&quot;\n&quot;);
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(&quot;\n&quot;);
fclose(fp); // closing the files
fclose(fb);
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top