VB如何读文本文件?
文本文件中只有一行文本“4243|12424|1|7|6”,但行尾没有0D或0A.用FileSystemObject的ReadLine读不到变量中,如何解决?...
文本文件中只有一行文本“4243|12424|1|7|6”,但行尾没有0D或0A .用File System Object的ReadLine读不到变量中,如何解决?
展开
2个回答
展开全部
读文件
Dim s As String
Dim filename As String
filename = shuxiang & xingzuo & ".txt"
Open filename For Input As #1
Do While Not EOF(1)
Line Input #1, s
Print s
Loop
Close #1
追加写文件
Dim i As Integer, n As Integer, a(6) As Integer
n = 6
Open "D:\1122.txt" For Append As #1
Randomize
For i = 1 To n
a(i) = Int(Rnd * 1000 + 1)
Print #1, a(i)
Next i
Close #1
覆盖写文件
Dim i As Integer, n As Integer, a(6) As Integer
n = 6
Open "D:\1122.txt" For output As #1
Randomize
For i = 1 To n
a(i) = Int(Rnd * 1000 + 1)
Print #1, a(i)
Next i
Close #1
'函数:一次性读文件至变量,非常快 Function GetFile(FileName As String) As String Dim i As Integer, s As String, BB() As Byte If Dir(FileName) = "" Then Exit Function i = FreeFile ReDim BB(FileLen(FileName) - 1) Open FileName For Binary As #i Get #i, , BB Close #i s = StrConv(BB, vbUnicode) GetFile = s End Function '调用举例: dim s as string s=GetFile("c:\1.txt")
展开全部
用ReadAll
追问
用line input 只能识别0D 0A 换行符,如果行尾只有0A就读不了。后来我改用File System Ojbect ,用ReadLine方法可以读行尾只有0A的行了,但是行尾没有0A这种它读不了了,读出来内容放在变量里是乱码,而这种情况line input 又可以读。 请问,VB中有没有一行一行读文本的好方法呢?
追答
Windows(DOS)系统的文本文件用0D0A作为换行符(VB中用常量vbCrLf表示);
UNIX系统的文本文件用0A作为换行符(VB中用常量vbLf表示);
Mac系统的文本文件用0D作为换行符(VB中用常量vbCr表示)。
下面的代码可以处理所有格式的文本文件:
Dim ss As String, s() As String
Open "1.txt" For Binary As #1
ss = Input(LOF(1), #1)
Close #1
ss = Replace(ss, vbCrLf, "^@^")
ss = Replace(ss, vbCr, "^@^")
ss = Replace(ss, vbLf, "^@^")
s = Split(ss, "^@^")
经过这样处理后,文本文件的每一行数据就放入数组s中了,只要逐个提取出s中的每个元素,就相当于逐行读取文本文件了。
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询