根据指定字符在文本中插入一行字符,给我个思路
文本格式如下:T01
T02
T02
T03
T02
T04
T04
T05
......
我设置一个关键字"T02",就在最后一个T02下面插入一行我想插入的字符(就是T04上面一行),然后保存
再比如我设置关键字“T04”,就在最后一个T04下面一行插入我想插入的字符(T05上面一行)然后保存。
最终文本如下:
T01
T02
T02
T03
T02
字符1
T04
T04
字符2
T05
......
请问,如何实现!!
谢谢! 高手呢,有爱心的人呢? 在百度知道也是你问的?
楼主看看我的代码:
Option Explicit
Private Sub InstLine(FileName As String, sKey As String, Text As String)
Dim aBuffer() As String
Dim sTemp As String, iFn As Integer
Dim lBufSize As Long
Dim lFlag As Long, p As Long
Dim i As Long
lBufSize = 32: ReDim aBuffer(lBufSize - 1)
i = -1: lFlag = 0
iFn = FreeFile()
Open FileName For Input As iFn
Do
If (EOF(iFn)) Then Exit Do
Line Input #iFn, sTemp
i = i + 1
If (i = lBufSize) Then
lBufSize = lBufSize + 8
ReDim Preserve aBuffer(lBufSize - 1)
End If
aBuffer(i) = sTemp
If (lFlag = 0) Then
If (sTemp = sKey) Then
lFlag = -1
p = i + 1
End If
Else
If (sTemp <> Text) Then p = i: lFlag = 0
End If
Loop
lBufSize = i
' 如果关键字不存在,添加到末尾
' 如果想加在开头,改为 then p=0
If (p = 0) Then p = -1
Close iFn
Open FileName For Output As iFn
lFlag = 0
For i = 0 To lBufSize
If (i = p) Then
Print #iFn, Text
lFlag = -1
End If
Print #iFn, aBuffer(i)
Next
If (lFlag = 0) Then Print #iFn, Text
Close iFn
End Sub
Private Sub Command1_Click()
Call InstLine("X:\temp\1.txt", "T02", "KKKKKKKK")
Call InstLine("X:\temp\1.txt", "T05", "QQQQQQ")
Call InstLine("X:\temp\1.txt", "XXXX", "WWWWWWWWW")
End Sub
Private Sub Command1_Click()
Call InstLine("X:\temp\1.txt", "T02", "KKKKKKKK")
Call InstLine("X:\temp\1.txt", "T05", "QQQQQQ")
Call InstLine("X:\temp\1.txt", "XXXX", "WWWWWWWWW")
End Sub
这儿的文件路径,按你自己实际情况写。
最好是传完整路径,以免出意外……
你在百度知道的贴子,可不可以等几天后再结贴呀?如果我的投诉处理了,结贴给我。 一个用二进制方式打开文件的方案
Private Sub Command1_Click()
Dim strTmp As String, bytTmp() As Byte, n As Long
Open "c:\test\test.txt" For Binary As #1
strTmp = String(LOF(1), Space(1))
Get #1, , strTmp
n = InStrRev(strTmp, Text1) + Len(Text1) + 1
Seek #1, 1
bytTmp = StrConv(Left(strTmp, n), vbFromUnicode)
Put #1, , bytTmp
Put #1, , Text2.Text & vbCrLf
bytTmp = StrConv(Mid(strTmp, n + 1), vbFromUnicode)
Put #1, , bytTmp
Close #1
End Sub
补充:VB , 基础类