本帖最后由 afan 于 2010-4-4 22:26 编辑
回复 6# 131738
修改了 _ReplaceStringInFile 函数,重命名为 __ReplaceStringInFile ,可自动识别编码
;Func __ReplaceStringInFile($szFileName, $szSearchString, $szReplaceString, $fCaseness = 0, $fOccurance = 1)
Local $iRetVal = 0
Local $nCount, $sEndsWith
; Check if file is readonly ..
If StringInStr(FileGetAttrib($szFileName), "R") Then Return SetError(6, 0, -1)
Local $hFile = FileOpen($szFileName, $FO_READ)
If $hFile = -1 Then Return SetError(1, 0, -1)
Local $s_TotFile = FileRead($hFile, FileGetSize($szFileName))
If StringRight($s_TotFile, 2) = @CRLF Then
$sEndsWith = @CRLF
ElseIf StringRight($s_TotFile, 1) = @CR Then
$sEndsWith = @CR
ElseIf StringRight($s_TotFile, 1) = @LF Then
$sEndsWith = @LF
Else
$sEndsWith = ""
EndIf
Local $aFileLines = StringSplit(StringStripCR($s_TotFile), @LF)
FileClose($hFile)
Local $mode = FileGetEncoding($szFileName)
If $mode = -1 Then $mode = 0
Local $hWriteHandle = FileOpen($szFileName, $FO_OVERWRITE + $mode)
If $hWriteHandle = -1 Then Return SetError(2, 0, -1)
For $nCount = 1 To $aFileLines[0]
If StringInStr($aFileLines[$nCount], $szSearchString, $fCaseness) Then
$aFileLines[$nCount] = StringReplace($aFileLines[$nCount], $szSearchString, $szReplaceString, 1 - $fOccurance, $fCaseness)
$iRetVal = $iRetVal + 1
If $fOccurance = 0 Then
$iRetVal = 1
ExitLoop
EndIf
EndIf
Next
For $nCount = 1 To $aFileLines[0] - 1
If FileWriteLine($hWriteHandle, $aFileLines[$nCount]) = 0 Then
FileClose($hWriteHandle)
Return SetError(3, 0, -1)
EndIf
Next
; Write the last record and ensure it ends with the same as the input file
If $aFileLines[$nCount] <> "" Then FileWrite($hWriteHandle, $aFileLines[$nCount] & $sEndsWith)
FileClose($hWriteHandle)
Return $iRetVal
EndFunc ;==>_ReplaceStringInFile
; |