file-io – 如何读取文件并写入文本文件?

前端之家收集整理的这篇文章主要介绍了file-io – 如何读取文件并写入文本文件?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想打开mis文件,复制所有数据并写入文本文件.

我的错文件.

文件名 – 1.mis

M3;3395;44;0;1;;20090404;094144;8193;3;0;;;;
M3;3397;155;0;2;;20090404;105941;8193;3;0;;;;
M3;3396;160;0;1;;20090404;100825;8193;3;0;;;;
M3;3398;168;0;2;;20090404;110106;8193;3;0;;;;

等……

以上数据应出现在具有相同文件名(1.txt)的文本文件中.

我试过这段代码.

Dim sFileText As String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
Input #iFileNo,sFileText
Loop
Close #iFileNo

Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Do While Not EOF(iFileNo)
Write #iFileNo,sFileText
Loop
Close #iFileNo

1.txt中没有保存任何内容.

使用Windows上默认安装的脚本运行时要容易得多

只需转到项目参考并检查Microsoft Scripting Runtime并单击“确定”.

然后你可以使用这个比默认文件命令更好的代码

Dim FSO As FileSystemObject
Dim TS As TextStream
Dim TempS As String
Dim Final As String
Set FSO = New FileSystemObject
Set TS = FSO.OpenTextFile("C:\Clients\Converter\Clockings.mis",ForReading)
'Use this for reading everything in one shot
Final = TS.ReadAll
'OR use this if you need to process each line
Do Until TS.AtEndOfStream
    TempS = TS.ReadLine
    Final = Final & TempS & vbCrLf
Loop
TS.Close

Set TS = FSO.OpenTextFile("C:\Clients\Converter\2.txt",ForWriting,True)
    TS.Write Final
TS.Close
Set TS = Nothing
Set FSO = Nothing

至于你的原始代码有什么问题,你正在阅读文本文件的每一行.

Input #iFileNo,sFileText

然后在这里写出来

Write #iFileNo,sFileText

sFileText是一个字符串变量,因此每次读取时,只需将sFileText的内容替换为刚刚读取的行的内容即可.

所以当你去写出来的时候,你所写的就是你读的最后一行,这可能是一个空白行.

Dim sFileText As String
Dim sFinal as String
Dim iFileNo As Integer
iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo,sFileText
sFinal = sFinal & sFileText & vbCRLF
Loop
Close #iFileNo

iFileNo = FreeFile 'Don't assume the last file number is free to use
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
Write #iFileNo,sFinal
Close #iFileNo

请注意,您不需要执行循环写入. sFinal包含准备一次写入的文件的完整文本.请注意,输入一次读取一行,因此附加到sFinal的每一行都需要在末尾附加CR和LF才能在MS Windows系统上正确写出.其他操作系统可能只需要一个LF(Chr $(10)).

如果您需要处理传入的数据,那么您需要执行类似的操作.

Dim sFileText As String
Dim sFinal as String
Dim vTemp as Variant
Dim iFileNo As Integer
Dim C as Collection
Dim R as Collection
Dim I as Long
Set C = New Collection
Set R = New Collection

iFileNo = FreeFile
Open "C:\Clients\Converter\Clockings.mis" For Input As #iFileNo
Do While Not EOF(iFileNo)
  Input #iFileNo,sFileText
  C.Add sFileText
Loop
Close #iFileNo

For Each vTemp in C
     Process vTemp
Next sTemp

iFileNo = FreeFile
Open "C:\Clients\Converter\2.txt" For Output As #iFileNo
For Each vTemp in R
   Write #iFileNo,vTemp & vbCRLF
Next sTemp
Close #iFileNo
原文链接:https://www.f2er.com/vb/255847.html

猜你在找的VB相关文章