VB操作文本文件的一个实例 |
|
www.nanhushi.com 佚名 不详 |
这是一个很有实际学习意义的VB操作文本文件的一个实例,学习VB的朋友一定要认真的看一看。 \'功能:删除、替换文本中一行,或者插入内容到文本中某一行 \'作者: soho_andy (冰) \'参数: \'strSourceFile 原始文件完整名 \'strTargetFile 生成新文件的完整名 \'intRow 操作的行数 Sub 操作文件中一行(strSourceFile As String, strTargetFile As String, intRow As Long) Dim filenum As Integer Dim fileContents As String Dim fileInfo() As String Dim i As Integer Dim j As Integer filenum = FreeFile Open strSourceFile For Binary As #filenum fileContents = Space(LOF(filenum)) Get #filenum, , fileContents Close filenum fileInfo = Split(fileContents, vbCrLf) \'取出源文件行数,按照回车换行来分隔成数组 filenum = FreeFile If Dir(strTargetFile, vbNormal) <> \"\" Then Kill strTargetFile End If Dim Filestr() As String \'删除一行代码块 Open strTargetFile For Append As #filenum \'循环每一行 For i = 0 To UBound(fileInfo) - 1 If i <> intRow - 1 Then Print #filenum, fileInfo(i) End If Next Close #filenum \'替换一行代码块 Open strTargetFile For Append As #filenum \'循环每一行 For i = 0 To UBound(fileInfo) - 1 If i = intRow - 1 Then Print #filenum, \"你要替换进去的内容\" End If Next Close #filenum \'插入一行代码块 Open strTargetFile For Append As #filenum \'循环每一行 For i = 0 To UBound(fileInfo) - 1 If i = intRow - 1 Then Print #filenum, \"你要插入到这行的内容\" Print #filenum, fileInfo(i) \'保留原来的行,位置后移一位 End If Next Close #filenum MsgBox \"完毕\" End Sub
\'另外一个解决实际问题的例子 \' \'设有文件a.txt,其中存放了两行数据,数据用逗号分隔,现在要读取第一行的奇数位置的数据写 入到另一个文本文件(b.txt)的第一行,类似地,把第二行的奇数位置的数据写入到第二行。 \'比如: \'文件a.txt如下: \'1,2,3,4,5 \'6,7,8,9,10 \'操作完成后,文件b.txt应为 \'1,3,5 \'6,8,10 \'作者: soho_andy (冰) \'参数: \'strSourceFile 原始文件完整名 \'strTargetFile 生成新文件的完整名 Sub 提取奇数位数据(strSourceFile As String, strTargetFile As String) Dim filenum As Integer Dim fileContents As String Dim fileInfo() As String Dim i As Integer Dim j As Integer Dim tmpDemData As String filenum = FreeFile Open strSourceFile For Binary As #filenum fileContents = Space(LOF(filenum)) Get #filenum, , fileContents Close filenum fileInfo = Split(fileContents, vbCrLf) \'取出源文件行数,按照回车换行来分隔成数组 filenum = FreeFile tmpDemData = \"\" If Dir(strTargetFile, vbNormal) <> \"\" Then Kill strTargetFile End If Dim Filestr() As String Open strTargetFile For Append As #filenum \'循环每一行 For i = 0 To UBound(fileInfo) - 1 Filestr = Split(Trim(fileInfo(i)), \",\") \'按照逗号分隔每一行的数据 tmpDemData = \"\" For j = 0 To UBound(Filestr) \'判断是否为奇数位 If (j Mod 2) = 0 Then tmpDemData = tmpDemData & Filestr(j) ElseIf j <> 0 And j <> UBound(Filestr) Then tmpDemData = tmpDemData & \",\" End If Next \'保存一行如目标文件 Print #filenum, tmpDemData Next Close #filenum MsgBox \"完毕\" End Sub Private Sub Command1_Click() 提取奇数位数据 \"d:\\aa.txt\", \"d:\\bb.txt\" End Sub
|
|
|
文章录入:杜斌 责任编辑:杜斌 |
|
上一篇文章: VB实例(设计模式能够自举的基类) 下一篇文章: 在VB中查找记录的方法 |
【字体:小 大】【发表评论】【加入收藏】【告诉好友】【打印此文】【关闭窗口】 |
|
|