Jump to content

_ReplaceStringInFile with different encoding


Recommended Posts

Hello,

I'm trying to use _ReplaceStringInFile with different encodings, but I can't seem to be able to do it.

I have seen a message about adding BOM, but I'm not exactly sure what I should add, where, and how.

Here is the part of my script that is not working.

$iEncoding = FileGetEncoding($Save_Array[1]) ; Retrieve the file encoding of the running script.
If @error Then
MsgBox(4096, "Error", "Could not obtain the file encoding.")
EndIf

For $i =1 To (UBound($Save_Array) - 1)
$handle =FileOpen($Save_Array[$i],$iEncoding)
If _ReplaceStringInFile($handle,$Old_Code, $New_Code, 1) = -1 Then
MsgBox(4096,"Error when replacing string", "Original code does not exist in file " & $Save_Array[$i])
If @error = 1 Then
MsgBox(4096, "Error when replacing string", "Cannot open file " & $Save_Array[$i])
ElseIf @error = 2 Then
MsgBox(4096, "Error when replacing string", "Cannot open temp file " & $Save_Array[$i])
ElseIf @error = 3 Then
MsgBox(4096, "Error when replacing string", "Cannot write to temp file " & $Save_Array[$i])
ElseIf @error = 4 Then
MsgBox(4096, "Error when replacing string", "Cannot delete original file " & $Save_Array[$i])
ElseIf @error = 5 Then
MsgBox(4096, "Error when replacing string", "Cannot rename/move temp file " & $Save_Array[$i])
ElseIf @error = 6 Then
MsgBox(4096, "Error when replacing string", "ReadOnly Attribute set for " & $Save_Array[$i])
EndIf
EndIf
FileClose($handle)
Next

When I try a string that I know is present in the file, this error message always comes up : MsgBox(4096,"Error when replacing string", "Original code does not exist in file " & $Save_Array[$i]) where $Save_Array[$i] is the correct file path.

I think the problem comes from the $handle variable, but if I'm not using it, it saves the modification in ANSI.

And the whole code just in case.

; *** Start added by AutoIt3Wrapper ***
#include <StructureConstants.au3>
; *** End added by AutoIt3Wrapper ***
#Region ;**** Directives created by AutoIt3Wrapper_GUI ****
#AutoIt3Wrapper_Icon=..\..\Steam\SteamApps\common\rome total war gold\rs2icon3.ico
#AutoIt3Wrapper_UseX64=n
#AutoIt3Wrapper_Add_Constants=n
#EndRegion ;**** Directives created by AutoIt3Wrapper_GUI ****
#include <GUIConstants.au3>
#include <GUIConstantsEx.au3>
#include <GuiEdit.au3>
#include <WindowsConstants.au3>
#include <EditConstants.au3>
#Include <Array.au3>
#Include <File.au3>
#include "GUIScrollbars_Ex.au3"
#include "RecFileListToArray.au3"


Opt('MustDeclareVars', 1)


; Main GUICreate
Global $hGUI
Global $Original_Edit
Global $New_Edit
Global $File_Name_Input
Global $Browse_button
Global $Path_Checkbox
Global $Save_Button
Global $All_Folders
; End

; Other variables
Global $Trim_Array
Global $File_Name

Global $CheckboxCount
Global $All_Array[1]
Global $Final_Array[1]
Global $Select_GUI
Global $iEncoding
Global $Old_Code
Global $New_Code
; End

_Main()

Func _Main()

; Create GUI
$hGUI = GUICreate('Multiple File Modifier', 1000, 800,-1,-1,-1,$WS_EX_ACCEPTFILES)

$Original_Edit = GUICtrlCreateEdit("Original Code",20,20,400,350,BitOR($ES_MULTILINE,$ES_WANTRETURN,$ES_AUTOHSCROLL,$ES_AUTOVSCROLL,$WS_VSCROLL))
_GUICtrlEdit_SetLimitText(GUICtrlGetHandle($Original_Edit),-1)

$New_Edit = GUICtrlCreateEdit("New Code",20,390,400,350,BitOR($ES_MULTILINE,$ES_WANTRETURN,$ES_AUTOHSCROLL,$ES_AUTOVSCROLL,$WS_VSCROLL))
_GUICtrlEdit_SetLimitText(GUICtrlGetHandle($New_Edit),-1)

$File_Name_Input = GUICtrlCreateInput("", 440, 20, 400, 20)
GUICtrlSetTip($File_Name_Input, "Enter the file name, or drag and drop the file into this box.")
GUICtrlSetState(-1, $GUI_DROPACCEPTED)

$Browse_button = GUICtrlCreateButton("Browse",860,16)



GUISetState()

; Run the GUI until the dialog is closed
While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
ExitLoop

Case $Browse_button
SplashTextOn("Multiple Files Modifier", "Browsing your hard drive. Please wait...", 250, 70)

$Old_Code = GUICtrlRead($Original_Edit)
$New_Code = GUICtrlRead($New_Edit)

MsgBox(4096, "test", $Old_Code)

$Trim_Array = StringSplit(GUICtrlRead($File_Name_Input),"\")
$File_Name = $Trim_Array[UBound($Trim_Array) - 1]
GUIDelete($hGUI)
_Display_Folders($File_Name)

EndSwitch
WEnd

GUIDelete()
EndFunc   ;==>_Main


Func _Display_Folders($fn)

Local $Folder_Array
Local $i, $j
Local $File_Array
Local $iOffsetLeft = 0, $iOffsetTop = 30
Local $Width = 1
Local $Quit_Button

FileChangeDir("..")

$Folder_Array = _FileListToArray(@WorkingDir, "Play*",2)
_ArrayInsert($Folder_Array,1,"Data")

$Select_GUI = GUICreate('Multiple File Modifier', 1000, 800)
$Quit_Button = GUICtrlCreateButton("Quit",450, 730,50,50)
$Save_Button = GUICtrlCreateButton("Save",500,730,50,50)
GUISetState()

For $i = 1 to (UBound($Folder_Array) - 1)

$File_Array = _RecFileListToArray(@WorkingDir & "\" & $Folder_Array[$i], $fn, 1,1,0,2)

If $File_Array = 0 Then
; Do nothing
Else
For $j = 1 to (UBound($File_Array) - 1)
_ArrayAdd($Final_Array, $File_Array[$j])
Next
EndIf
Next

$CheckboxCount = (UBound($Final_Array) - 1)

Local $CheckboxArray[$CheckboxCount + 1]

$All_Folders = GUICtrlCreateCheckbox("All folders", 0, 0)
For $CheckboxCounter = 1 To $CheckboxCount
_ArrayAdd($All_Array,GUICtrlCreateCheckbox($Final_Array[$CheckboxCounter], $iOffsetLeft, $iOffsetTop))
$iOffsetTop += 20
If IsInt($CheckboxCounter / 35) Then
$Width = $Width + 1
$iOffsetLeft += 1000
$iOffsetTop = 30
EndIf
$CheckboxArray[$CheckboxCounter - 1] = $CheckboxCounter
Next

SplashOff()
_GUIScrollbars_Generate($Select_GUI, $Width * 1000)


While 1
Switch GUIGetMsg()
Case $GUI_EVENT_CLOSE
ExitLoop

Case $Quit_Button
GUIDelete()


Case $All_Folders
If GUICtrlRead($All_Folders) = 1 Then
For $i = 1 To $CheckboxCount
GUICtrlSetState($All_Array[$i],$GUI_CHECKED)
Next
Else
For $i = 1 To $CheckboxCount
GUICtrlSetState($All_Array[$i],$GUI_UNCHECKED)
Next
EndIf

Case $Save_Button
SplashTextOn("Multiple Files Modifier", "Modifying files. Please wait...", 250, 70)
_Save()
SplashOff()


EndSwitch
WEnd



EndFunc


Func _Save()

Local $Save_Array[1]
Local $handle


For $i = 1 To $CheckboxCount
        If GUICtrlRead($All_Array[$i]) = 1 Then
            _ArrayAdd($Save_Array, $All_Array[$i])
$Save_Array[UBound($Save_Array) - 1] = $Final_Array[$i]
        EndIf
Next

$iEncoding = FileGetEncoding($Save_Array[1]) ; Retrieve the file encoding of the running script.
If @error Then
MsgBox(4096, "Error", "Could not obtain the file encoding.")
EndIf

For $i =1 To (UBound($Save_Array) - 1)
$handle =FileOpen($Save_Array[$i],$iEncoding)
If _ReplaceStringInFile($handle,$Old_Code, $New_Code, 1) = -1 Then
MsgBox(4096,"Error when replacing string", "Original code does not exist in file " & $Save_Array[$i])
If @error = 1 Then
MsgBox(4096, "Error when replacing string", "Cannot open file " & $Save_Array[$i])
ElseIf @error = 2 Then
MsgBox(4096, "Error when replacing string", "Cannot open temp file " & $Save_Array[$i])
ElseIf @error = 3 Then
MsgBox(4096, "Error when replacing string", "Cannot write to temp file " & $Save_Array[$i])
ElseIf @error = 4 Then
MsgBox(4096, "Error when replacing string", "Cannot delete original file " & $Save_Array[$i])
ElseIf @error = 5 Then
MsgBox(4096, "Error when replacing string", "Cannot rename/move temp file " & $Save_Array[$i])
ElseIf @error = 6 Then
MsgBox(4096, "Error when replacing string", "ReadOnly Attribute set for " & $Save_Array[$i])
EndIf
EndIf
FileClose($handle)
Next

EndFunc

Thanks in advance.

Link to comment
Share on other sites

First, if the _FileGetEncoding fail, the return value is -1.

Second, you can't FileOpen a file with a value of -1.

Third, _ReplaceStringInFile uses a filename with full path and not a handle returned from a FileOpen, it won't ever work that way.

EDIT: Fourth, if the encoding is in ANSI, the file open will be in read only mode, so you couldn't edit the file even if you COULD use the file handle.

Edited by BrewManNH

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

First, if the _FileGetEncoding fail, the return value is -1.

Second, you can't FileOpen a file with a value of -1.

Third, _ReplaceStringInFile uses a filename with full path and not a handle returned from a FileOpen, it won't ever work that way.

EDIT: Fourth, if the encoding is in ANSI, the file open will be in read only mode, so you couldn't edit the file even if you COULD use the file handle.

Hum, alright thanks.

But then my question remains, is there a way to replace text that might be ANSI or UTF16 Little Endian?

Link to comment
Share on other sites

Use FileOpen with the UTF format you want it in, write it to a new file, close that file, then copy/move the new file to the old file's name.

If I posted any code, assume that code was written using the latest release version unless stated otherwise. Also, if it doesn't work on XP I can't help with that because I don't have access to XP, and I'm not going to.
Give a programmer the correct code and he can do his work for a day. Teach a programmer to debug and he can do his work for a lifetime - by Chirag Gude
How to ask questions the smart way!

I hereby grant any person the right to use any code I post, that I am the original author of, on the autoitscript.com forums, unless I've specifically stated otherwise in the code or the thread post. If you do use my code all I ask, as a courtesy, is to make note of where you got it from.

Back up and restore Windows user files _Array.au3 - Modified array functions that include support for 2D arrays.  -  ColorChooser - An add-on for SciTE that pops up a color dialog so you can select and paste a color code into a script.  -  Customizable Splashscreen GUI w/Progress Bar - Create a custom "splash screen" GUI with a progress bar and custom label.  -  _FileGetProperty - Retrieve the properties of a file  -  SciTE Toolbar - A toolbar demo for use with the SciTE editor  -  GUIRegisterMsg demo - Demo script to show how to use the Windows messages to interact with controls and your GUI.  -   Latin Square password generator

Link to comment
Share on other sites

Works like a charm, thanks a lot.

Here's what I did, maybe it will help someone someday.

$iEncoding = FileGetEncoding($Save_Array[1]) ; Retrieve the file encoding of the running script.
If @error Then
MsgBox(4096, "Error", "Could not obtain the file encoding.")
EndIf

For $i =1 To (UBound($Save_Array) - 1)
$handle = FileOpen($Save_Array[$i], 2 + $iEncoding)

; Check if file opened for reading OK
If $handle = -1 Then
MsgBox(0, "Error", "Unable to open " & $Save_Array[$i])
EndIf

$Text = FileRead($handle)
If @error = 1 Then
MsgBox(4096,"Error", "Unable to read" & $Save_Array[$i])
EndIf

FileClose($handle)


$Replaced_Text = StringReplace($Text, $Old_Code, $New_Code,0,1)
If $Replaced_Text = "" Then
MsgBox(4096,"Error when replacing string", "Original code does not exist in file " & $Save_Array[$i])
EndIf


$handle = FileOpen(@TempDir & "\" & $File_Name, 2 + $iEncoding)

If FileWrite($handle, $Replaced_Text) = 0 Then
MsgBox(4096, "Error", "Unable to write " & @TempDir & "\" & $File_Name)
EndIf

If FileCopy(@TempDir & "\" & $File_Name, $Save_Array[$i], 1) = 0 Then
MsgBox(4096, "Error", "Failed to copy from temp file.")
EndIf

FileDelete(@TempDir &"\" & $File_Name)

FileClose($handle)
Next
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...