View Single Post
Bugsy
AMX Mod X Moderator
Join Date: Feb 2005
Location: NJ, USA
Old 05-23-2015 , 10:49   Re: Edit a word inside a text file
Reply With Quote #8

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 szDestFile64 ] , szBufferDATA_BUFFER_SIZE ] , iLen iBytesRead iMaxBytesToRead;
    
    
formatexszDestFile charsmaxszDestFile ) , "%s_tmp" szFile );
    
    if ( ( 
iSrcFile fopenszFile "r" ) ) && ( iDestFile fopenszDestFile "w+" ) ) )
    {
        
iMaxBytesToRead = ( strlenszReplaceWith ) > strlenszFind ) ) ? ( DATA_BUFFER_SIZE ) : charsmaxszBuffer );
        
        while ( ( 
iBytesRead fread_blocksiSrcFile szBuffer iMaxBytesToRead BLOCK_CHAR ) ) )
        {
            
szBufferiBytesRead ] = EOS;
        
            
replace_allszBuffer charsmaxszBuffer ) , szFind szReplaceWith );
            
iLen strlenszBuffer );

            
fwrite_blocksiDestFile szBuffer iLen BLOCK_CHAR );
        }
        
        
fcloseiSrcFile );
        
fcloseiDestFile );
    }
    
    return ( 
iSrcFile && iDestFile && delete_fileszFile ) && rename_fileszDestFile szFile ) );

__________________

Last edited by Bugsy; 05-24-2015 at 00:32.
Bugsy is online now