现在有一个文本文件client.conf(就是一个配置文件),我想用代码把它的每一行读出来,然后获得有“remote”这个字符串的那一行(那行内容是:remeot+IP+端口号,如:remote 192.168.1.1 1194),把它替换成:remote+用户输入的IP+1194,再写回去,大概端口号不用改吧
注意:是把原来那行替换掉再写回原来那行,就是必须是原文件的remote的那行还有一个,就是替换完成之后,再把源文件写到另一个地方去(就是生成一个源文件的副本client2.conf)这两个我不太会,请大侠们指教,谢谢~!

解决方案 »

  1.   

    如果你的文件符合*.ini(配置设置)文件的语法,可以用
    WritePrivateProfileString
    GetPrivateProfileInt
    GetPrivateProfileString
    这组API函数完成。
      

  2.   

    Option ExplicitSub Main()
        Dim hFile1 As Integer, hFile2 As Integer
        Dim sLine As String
        
        FileCopy "C:\client.conf", "C:\client2.conf"
        
        hFile2 = FreeFile()
        Open "C:\client2.conf" For Output Access Write As #hFile2
        
        hFile1 = FreeFile()
        Open "C:\client.conf" For Input Access Read As #hFile1
        
        While Not EOF(hFile1)
            Line Input #hFile1, sLine
            '按需要替换sLline'
            Print #hFile2, sLine
        Wend
        
        Close #hFile1
        Close #hFile2
    End Sub
      

  3.   

    好,Tiger_Zhao 帮我解决的是第二个问题,我一会看看好使不。那第一个呢?写回原来的那个文件?谁来~~
      

  4.   

    FileCopy 以后两个文件内容相同,所以将两个 Open 语句的文件名交换一下就可以了。
      

  5.   

    Dim strTmp As StringOpen "client.conf" For Input As #1
    Open "client2.conf" For Output As #2
    Do Until EOF(1)
        Line Input #1, strTmp
        If InStr(strTmp, "remote") > 0 Then 
            strTmp = "remote " & Trim(Text1) & " 1194"
        End If
        Print #2, strTmp
    Loop
    Close #2
    Close #1
      

  6.   

    楼主参考一下我的这段代码:
    Sub ProcFile()    Dim iFileA%, iFileB%, iOffset%
        Dim strSPath$, strDPath$, strFileName$
        Dim strTemp$, strInputIP$
        
        strSPath = "C:\Windows\"    '源文件路径
        strDPath = "E:\Temp\"       '输出副本的路径
        strFileName = "client.conf" '文件名
        strInputIP = "118.125.172.116"
        '先变换一下
        strSPath = strSPath & strFileName
        strDPath = strDPath & strFileName
        '处理文件
        iFileA = FreeFile()
        Open strSPath For Input Lock Write As #iFileA
        iFileB = FreeFile()
        Open strDPath For Output Lock Read As #iFileB
        While (Not EOF(iFileA))
            Line Input #iFileA, strTemp
            strTemp = "remote 118.12.5.26 8619"
            If (InStr(1, strTemp, "remote ", vbTextCompare) = 1) Then
                '读到 remote 开头的行
                iOffset = InStr(8, strTemp, " ")
                strTemp = Replace(strTemp, Mid$(strTemp, 8, iOffset - 8), strInputIP)
            End If
            Print #iFileB, strTemp  '先直接输出副本
        Wend
        Close                       '全部关闭
        'Kill strSPath               '删除原始文件
        FileCopy strDPath, strSPath '用处理后的文件替换源文件End Sub
      

  7.   

    把这一句删掉:
    strTemp = "remote 118.12.5.26 8619"我测试后忘记了删……-_-!
      

  8.   

    to: 10F  这位兄台,没那么严重吧!
      你有什么高见,不妨说明白一些,好向你学习一下。
      或者把你的巧妙绝伦的代码贴出来,让我开一下眼见!!!
      

  9.   

    楼主太监了?
    用我在2楼、4楼的方法就可以实现备份并改写原文件。
    Chen8013在8楼甚至将替换的方法都给出来了。这贴可以结了。