Raised This Month: $ Target: $400
 0% 

Edit a word inside a text file


Post New Thread Reply   
 
Thread Tools Display Modes
Author Message
fysiks
Veteran Member
Join Date: Sep 2007
Location: Flatland, USA
Old 05-17-2015 , 13:18   Re: Edit a word inside a text file
Reply With Quote #1

Have you tried LoadFileForMe()?
__________________
fysiks is offline
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 #2

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 offline
Reply



Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is On
HTML code is Off

Forum Jump


All times are GMT -4. The time now is 01:16.


Powered by vBulletin®
Copyright ©2000 - 2024, vBulletin Solutions, Inc.
Theme made by Freecode