Reg - 错误输入文件末尾 - VbScript

时间:2013-01-23 13:38:52

标签: vbscript

我编写了一个简单的程序来使用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

1 个答案:

答案 0 :(得分: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
>>