0

我编写了一个简单的程序来使用 写入和读取文本文件中的数据FileSystemObject,但它不起作用并给我一个运行时错误:

输入文件末尾。

请让我知道我在这里犯的错误。

'Here is the Program - 

Dim Fso    'Reference obect to File system
Dim TxtObj 'Reference to Text stream object
Dim Txt    'Reference to Text stream object to open file
Dim i      'To Read Text in file

Set Fso = CreateObject("Scripting.FileSystemObject")

Set Txtobj = Fso.CreateTextFile("C:\Users\ACER\Desktop\Project Folder\NewText_3.txt")

Txtobj.Write("Hello")

Txtobj.Close

Set Txt = Fso.OpenTextFile("C:\Users\ACER\Desktop\Project Folder\NewText_3.txt",1)

Do while Txt.AtEndOfStream<>1
  i = Txt.Read(1)
Loop

Msgbox i

Txt.close
4

1 回答 1

1
Option Explicit ' safety belt

Const FSpec = "14481096.txt" ' dry the file name

Dim Fso 'Reference object to File system
Set Fso = CreateObject("Scripting.FileSystemObject")

Dim TxtObj 'Reference to Text stream object (used for rwrite and read)
Set Txtobj = Fso.CreateTextFile(FSpec)

Txtobj.WriteLine "Hello"
Txtobj.Close

Dim Letter 'To Read Text in file (each letter)
Set Txtobj = Fso.OpenTextFile(FSpec)  ' ForReading is the default, no need for magic number 1)
Do Until Txtobj.AtEndOfStream ' never compare boolean values against boolean literals
                              ' or - worse - values of other types you *hope* VBScript
                              ' will convert correctly
   Letter = Txtobj.Read(1) ' letter
   WScript.Echo "got", Letter
Loop
Txtobj.Close

输出:

cscript 14481096.vbs
got H
got e
got l
got l
got o
got     <-- aka cr
got     <-- aka lf (in case you are wondering)

额外提示:

>> WScript.Echo CInt(True), CInt(False)
>>
-1 0
>>
于 2013-01-23T15:36:55.990 回答