【问题标题】:Reg - Error Input Past End of File - VbScriptReg - 错误输入超过文件结尾 - VbScript
【发布时间】:2013-01-23 13:38:52
【问题描述】:

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

【问题讨论】:

    标签: vbscript


    【解决方案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
    >>
    

    【讨论】:

    • 非常感谢,我在下面的程序中进行了一些更改,即正在写入文本直到流结束而不是读取,并且我收到运行时错误 - 错误文件模式。
    • Dim Fso '文件系统引用对象 Dim TxtObj '文本流对象引用 Dim Txt '文本对象文件引用 Set Fso = CreateObject("Scripting.FileSystemObject") Set Txtobj = Fso.CreateTextFile( "C:\Users\ACER\Desktop\Project Folder\NewText_5.txt") 一直执行到 Txtobj.AtEndofStream Txtobj.Write("Hello") Loop Txtobj.Close
    • @user1925406 幸运的是,如果您正在写作,则没有“直到文件结束”的概念。
    猜你喜欢
    • 1970-01-01
    • 2023-04-05
    • 1970-01-01
    • 1970-01-01
    • 2013-10-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多