This will replace every instance of szFind with szReplaceWith in a file. Keep in mind that this reads the file in DATA_BUFFER_SIZE chunks and if szFind is located between chunks then it will not get replaced. Easiest way to avoid this is to size DATA_BUFFER_SIZE larger than the file, or use a method that reads 1 line at a time. If you're using 1.8.3+, use replace_string() instead of replace_all().
Edit: Updated it to handle szReplaceWith[] that is larger than szFind[]. If szReplaceWith is larger, it will use half of the data buffer for reading file data, and the other half to allow for the extra characters in szReplaceWith. If szReplaceWith is <= szFind, it will use the full buffer for reading file data. If OP can give more details about the potential size of this file, I can probably tweak it to be more reliable. If all else fails, a line-by-line replacer may be better.
PHP Code:
ReplaceTextInFile( "my_file.txt" , "find this" , "replace with this" );
//Returns 1 on success, 0 on fail.
PHP Code:
ReplaceTextInFile( const szFile[] , const szFind[] , const szReplaceWith[] )
{
const DATA_BUFFER_SIZE = 1024;
new iSrcFile , iDestFile , szDestFile[ 64 ] , szBuffer[ DATA_BUFFER_SIZE ] , iLen , iBytesRead , iMaxBytesToRead;
formatex( szDestFile , charsmax( szDestFile ) , "%s_tmp" , szFile );
if ( ( iSrcFile = fopen( szFile , "r" ) ) && ( iDestFile = fopen( szDestFile , "w+" ) ) )
{
iMaxBytesToRead = ( strlen( szReplaceWith ) > strlen( szFind ) ) ? ( DATA_BUFFER_SIZE / 2 ) : charsmax( szBuffer );
while ( ( iBytesRead = fread_blocks( iSrcFile , szBuffer , iMaxBytesToRead , BLOCK_CHAR ) ) )
{
szBuffer[ iBytesRead ] = EOS;
replace_all( szBuffer , charsmax( szBuffer ) , szFind , szReplaceWith );
iLen = strlen( szBuffer );
fwrite_blocks( iDestFile , szBuffer , iLen , BLOCK_CHAR );
}
fclose( iSrcFile );
fclose( iDestFile );
}
return ( iSrcFile && iDestFile && delete_file( szFile ) && rename_file( szDestFile , szFile , 1 ) );
}
__________________