lulubobo27 发表于 2011-5-13 16:02:02

关于用_ReplaceStringInFile 函数替换文件中字符串产生乱码问题

最近写了个脚本想替换文件(非英文文件)中指定字符串,结果替换完后,原来的文件全成乱码了,是什么地方出问题了?有其他可替代的函数可用吗?

love5173 发表于 2011-5-13 17:37:00

最好能提供你操作的文件原件,如果不方便可以修改后再发出来,udf都是经过测试的,你可以说他效率低,但是功能有问题不大可能,或许是你运用的不好,发附件吧!

lulubobo27 发表于 2011-5-14 15:05:02

用SciTE打开执行前后的文件,对比后抓的图:


这是测试的代码:#include <File.au3>

$filename = "D:\Temp\Test.mif"
$find = "Test222"
$replace = "Test111"

$retval = _ReplaceStringInFile($filename,$find,$replace)

if $retval = -1 then
        msgbox(0, "ERROR", "The pattern could not be replaced in file: " & $filename & " Error: " & @error)
        exit
else
        msgbox(0, "INFO", "Found " & $retval & " occurances of the pattern: " & $find & " in the file: " & $filename)
EndIf这是测试的文件 

大侠,帮忙看一下,_ReplaceStringInFile 这个函数是不是不能修改含有希腊等特殊字符的文件?

lulubobo27 发表于 2011-5-14 15:07:57

另,SciTE查看的文件编码是UTF-8或16才能看到希腊字母与汉字

3mile 发表于 2011-5-14 15:37:37

没测试过,不知道有没有效
#include <File.au3>

$filename = "Test.mif"
$find = "Test222"
$replace = "Test111"
$hFile=FileOpen($filename,256)
$str=FileRead($hFile)
FileClose($hFile)
$str=StringReplace($str,$find,$replace,0,1)

$wFile=FileOpen(@ScriptDir&"\out.txt",2+256)
FileWrite($wFile,$str)
FileClose($wFile)

lulubobo27 发表于 2011-5-14 17:02:02

非常感谢 3mile  的回答,所提供的代码对测试文件有效。
不知为何_ReplaceStringInFile 函数会有这个 Bug?

lulubobo27 发表于 2011-5-14 17:28:32

刚改了下用户函数 File.au3, 把_ReplaceStringInFile 函数中的打开文件模式用由 $FO_OVERWRITE改为 3mile 建议的2+256(即utf-8写入模式),也可以不产生乱码了。
可见,有UTF-8字符的文件要以这个模式打开文件才不产生乱码。

新问题:如果不知道文件是什么类型的代码,该以何模式替换字符呢?

3mile 发表于 2011-5-14 22:41:12

刚改了下用户函数 File.au3, 把_ReplaceStringInFile 函数中的打开文件模式用由 $FO_OVERWRITE改为 3mil ...
lulubobo27 发表于 2011-5-14 17:28 http://www.autoitx.com/images/common/back.gif
#include <winapi.au3>

$filename = "out.txt"
$CODE = _GetFileCode($filename)
MsgBox(0, 0, $CODE)

Func _GetFileCode($file)
        Local $nBytes
        $tBuffer = DllStructCreate("byte[" & 2 & "]")
        $hFile = _WinAPI_CreateFile($file, 2, 2)
        _WinAPI_ReadFile($hFile, DllStructGetPtr($tBuffer), 2, $nBytes)
        _WinAPI_CloseHandle($hFile)
        $sText = DllStructGetData($tBuffer, 1)
        Switch $sText
                Case "0xEFBB"
                        Return "UTF-8"
                Case "0XFEFF"
                        Return "Unicode big endian"
                Case "0XFEFE"
                        Return "Unicode"
                Case Else
                        Return "ANSI"
        EndSwitch
EndFunc   ;==>_GetFileCode
页: [1]
查看完整版本: 关于用_ReplaceStringInFile 函数替换文件中字符串产生乱码问题