Reg - Error Input Past End of File - VbScript - vbscript

I wrote a simple program to write and read data from text file using FileSystemObject, but it doesn't work and gives me a runtime error:
Input Past End of File.
Kindly let me know the mistake I made here.
'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

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
output:
cscript 14481096.vbs
got H
got e
got l
got l
got o
got <-- aka cr
got <-- aka lf (in case you are wondering)
Extra hint:
>> WScript.Echo CInt(True), CInt(False)
>>
-1 0
>>

Related

The OpenTextFile is overriding opened text file by clearing it

I am currently having a problem with OpenTextFile. I created a script over a year ago. Recently, the script started giving me problems. It's clearing the first text file and giving me an error.
Set objArgs = WScript.Arguments
myFile = objArgs(0)
numberofTXT = objArgs(1)
line = objArgs(2)
Set f = CreateObject("Scripting.FileSystemObject").OpenTextFile(myFile, line)
d = f.ReadLine
Set objFSO=CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
objFile.Write d & vbCrLf
objFile.Close
This is a super basic script I wrote to explain my issue. Takes in 3 files as arguments. For example LOL.txt, Hi.txt, and a specific line of LOL.txt (Why did 13-year-old me give examples using the word Lol, oh my gosh). This is meant to read the first file and write the data from the first file to the second file.
This issue was due to my current understanding (when I posted this) and not knowing what documentation was. I was self-taught. Please make sure to read the documentation if you have any issues with OpenTextFile and make sure your arguments are correct for the function.
Read and apply the OpenTextFile Method reference:
Opens a specified file and returns a TextStream object that can be
used to read from, write to, or append to the file.
Syntax
object.OpenTextFile(filename[, iomode[, create[, format]]])
Arguments
object   Required. Object is always the name of a FileSystemObject.
filename Required. String expression that identifies the file to open.
iomode   Optional. Can be one of three constants: ForReading, ForWriting, or ForAppending.
create   Optional. Boolean value that indicates whether a new file can be created if the specified filename doesn't exist. The value
is True if a new file is created, False if it isn't created. If
omitted, a new file isn't created.
format   Optional. One of three Tristate values used to indicate the format of the opened file (TristateTrue = -1 to open the file as
Unicode, TristateFalse = 0 to open the file as ASCII,
TristateUseDefault = -2 to open the file as the system default). If
omitted, the file is opened as ASCII.
Settings
The iomode argument can have any of the following settings:
Constant Value Description
ForReading 1 Open a file for reading only. You can't write to this file.
ForWriting 2 Open a file for writing.
ForAppending 8 Open a file and write to the end of the file.
Read CreateTextFile Method reference as well. Then, the following commented code snippet could help:
Const ForReading = 1
Set objArgs = WScript.Arguments
myFile = objArgs(0) ' file to read
numberofTXT = objArgs(1) ' file to write
line = objArgs(2) ' line serial number to write into output file
' (or number of lines?)
Set objFSO = CreateObject("Scripting.FileSystemObject")
outFile=numberofTXT
Set objFile = objFSO.CreateTextFile(outFile,True)
Set f = objFSO.OpenTextFile(myFile, ForReading)
lineindex = 1
Do until f.AtEndOfStream
d = f.ReadLine
if lineindex = line Then ' only take the line-th line
objFile.Write d & vbCrLf ' or objFile.WriteLine d
Exit Do ' transfers control to the statement immediately following Loop statement
End If
lineindex = lineindex + 1
Loop
objFile.Close
f.Close

Is there a way to use data from a read file in VB as an active string variable?

I'm trying to make a script that reads file data in a text file as a string then can be called as another variable. I've been working on it for a while.
Code that will open the file:
Option Explicit
Dim fso, BC1
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
MsgBox BC1.ReadLine
BC1.Close
I need to take the 1 line of data read from this textfile and set it as another variable in string format (ie: Dim Variable1 As String = BC1 data). Any ideas? If I can get the data I want from the file as a string, the rest of my script will execute like it should.
To save all file data in a text file to strBC1 variable (string variant):
Option Explicit
Dim fso, BC1, strBC1
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
strBC1 = BC1.ReadAll
BC1.Close
To read a text file line by line and save 1st non-empty line to strLine variable (string variant):
Option Explicit
Dim fso, BC1, strLine
Set fso = CreateObject("Scripting.FileSystemObject")
Set BC1 = fso.OpenTextFile("C:\Users\GDoe\Desktop\BC1.txt",1)
Do Until BC1.AtEndOfStream
strLine = BC1.Readline
If strLine <> "" Then
Exit Do 'stops looping and transfers control
' to the statement immediately following the Loop
End If
Loop
BC1.Close

Read the line from a text file with the particular string using VBScript

I have a text file that contains log data. I have retrieve Serial No, Output status, Pin No etc from the log file.
My log file look like below. It has lot of contents.
"FORMAT=U2"
"BEGIN HEADER"
"TS=600581"
"ST=1001038"
"TC=60055"
"PIN=100577"
"SN=GXT220.1"
I have to read the file and print PIN is 100577 and Serial No is GXT220.1. I have do the same for may files and the line no is not same for all the files.
Not sure if this is what you want ---> Reading through the textfile and extract out specific information in a line with constant indicator.
If so, this is what i will do.
Option Explicit
Dim FSO, ReadTextFile ' object
Dim Textline ' string/variant
Dim PinNumber, Serial ' Output
FSO = CreateObject("Scripting.FileSystemObject")
Set ReadTextFile = FSO.OpenTextFile("File.txt", 1) ' Open text with read only mode
Do Until ReadTextFile.AtEndOfStream
Textline = ReadTextFile.Readline()
If Instr(Textline, "PIN=") Then ' If textline contain string "PIN="
PinNumber = Split(Textline, "=")(1) ' Split the textline with "=" indicator
End If
If Instr(Textline, "SN=") Then
Serial = Split(Textline, "=")(1)
End If
Loop ' Read through every line
This example only works if you have only one indicator in one file. And also your indicator is the same to all txt file. Hope it helps :)
Use
.ReadAll() to read a file into a string
a RegExp to parse the string
a Dictionary to store/access the values
As in:
Option Explicit
Dim goFS : Set goFS = CreateObject("Scripting.FileSystemObject")
Dim s : s = goFS.OpenTextFile("43009791.txt").ReadAll()
Dim r : Set r = New RegExp
r.Global = True
r.Multiline = True
r.Pattern = "^""(\w+)=([^""]+)"""
Dim d : Set d = CreateObject("Scripting.Dictionary")
Dim m
For Each m In r.Execute(s)
d(m.Submatches(0)) = m.Submatches(1)
Next
Dim k
For Each k In d.Keys()
WScript.Echo k, "=>", d(k)
Next
output:
cscript 43009791.vbs
FORMAT => U2
TS => 600581
ST => 1001038
TC => 60055
PIN => 100577
SN => GXT220.1

Windows script host error 800A0046

I'm receiving the following error when I run my program:
Script: C: My Folder\Tracking Macro.vbs
Line: 70
Char: 1
Error: Permission denied
Code: 800A0046
Source: Microsoft VBScript runtime error
Here is the code.
' Set constants for reading, writing, and appending files
Const ForReading = 1, ForWriting = 2, ForAppending = 8
' Sets up the object variables.
Dim objExcel, objFSO, objTextFile, objCSVFile
' Sets up the string variables.
Dim strTextFile, strHeadLine, strTextLine, strCSVFile
' Sets up the all the string variables for the program.
Dim Desktop, todaysDate, usageDate, myDay, myMonth, myYear
'This creates the required Objects
Set objExcel = CreateObject("Excel.application")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set WshShell = WScript.CreateObject("WScript.Shell")
Desktop = WshShell.ExpandEnvironmentStrings("%USERPROFILE%") & "\" & "Desktop"
' Set date for date stamp in file name and sheet name
todaysDate = Date()
myMonth = Month(todaysDate)
If Len(myMonth)=1 Then myMonth="0" & myMonth
myDay = Day(todaysDate)
If Len(myDay)=1 Then myDay="0" & myDay
myYear = Right(Year(todaysDate), 2)
usageDate = myMonth & myDay & myYear
' Set up the origin and destination files
strTextFile = (Desktop & "\MacroTracker.txt")
strCSVFile = "C: My Folder\TrackingTesting" & usageDate & ".csv"
strHeadLine = "Macro Name,User ID,Ran At,Contracted Rate,BHVN,Set Number,Provider TIN,Billed Charge,Service Code"
Set objTextFile = objFSO.OpenTextFile(strTextFile)
' Read the entire origin file
Do Until objTextFile.AtEndOfStream
strTextLine = objTextFile.ReadLine
Loop
If (objFSO.FileExists(strCSVFile)) Then
' Create object for appending current TXT file to CSV file
Set objCSVFile = objFSO.OpenTextFile(strCSVFile, ForAppending, True)
' Write an append line of data to the CSV file
objCSVFile.WriteLine strTextLine
Else
' Create CSV file to write to with today's date
Set objCSVFile = objFSO.CreateTextFile(strCSVFile, True)
' Create object for appending current TXT file to CSV file
Set objCSVFile = objFSO.OpenTextFile(strCSVFile, ForAppending, True)
' Write initial header for the CSV file
objCSVFile.WriteLine strHeadLine
' Write an append line of data to the CSV file
objCSVFile.WriteLine strTextLine
End If
' Wait for file to be written to
Wscript.Sleep 600
' Delete origin file to prevent user tampering
objFSO.DeleteFile(strTextFile)
Line 70 is the very last line where I'm deleting the text file. According to every help site I've seen, this is EXACTLY how it should be typed. I checked the permissions of the file...I have full control, so I should be able to delete it. It's only meant to be a temp file, not something that stores info for long periods of time.
I've checked Microsoft and all other help sites for the error code and have not found any solutions that can help me. I'm hoping someone may have ran into a similar instance and found a resolution.
Your file is still open. You need to add this:
objTextFile.Close
somewhere before you try to delete it. I would put it right after you're done using the file.

Read and write binary file in VBscript

I used earlier ADODB.Stream to read and to write binary file here is the link for that
How to concatenate binary file using ADODB.stream in VBscript
it works fine the only problem is ADODB.stream is disabled on windows 2003 server,
Is there another way i can read 3 files in binary mode and concatenate them or store them in one file in VBscript
thank you
Jp
Based on Luc125 and Alberto answers here are the 2 reworked and simplified functions:
The Read function
Function readBinary(strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
Dim oFile: Set oFile = oFSO.GetFile(strPath)
If IsNull(oFile) Then MsgBox("File not found: " & strPath) : Exit Function
With oFile.OpenAsTextStream()
readBinary = .Read(oFile.Size)
.Close
End With
End Function
The Write function
Function writeBinary(strBinary, strPath)
Dim oFSO: Set oFSO = CreateObject("Scripting.FileSystemObject")
' below lines pupose: checks that write access is possible!
Dim oTxtStream
On Error Resume Next
Set oTxtStream = oFSO.createTextFile(strPath)
If Err.number <> 0 Then MsgBox(Err.message) : Exit Function
On Error GoTo 0
Set oTxtStream = Nothing
' end check of write access
With oFSO.createTextFile(strPath)
.Write(strBinary)
.Close
End With
End Function
I had a similar problem a year ago. We know that the TextStream objects are intended for ANSI or Unicode text data, not binary data; their .readAll() method produces a corrupted output if the stream is binary. But there is workaround. Reading the characters one by one into an array works fine. This should allow you to read binary data into VB strings, and write it back to disk. When further manipulating such binary strings do not forget that certain operations may result into broken strings because they are intended for text only. I for one always convert binary strings into integer arrays before working with them.Function readBinary(path)
Dim a
Dim fso
Dim file
Dim i
Dim ts
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.getFile(path)
If isNull(file) Then
MsgBox("File not found: " & path)
Exit Function
End If
Set ts = file.OpenAsTextStream()
a = makeArray(file.size)
i = 0
' Do not replace the following block by readBinary = by ts.readAll(), it would result in broken output, because that method is not intended for binary data
While Not ts.atEndOfStream
a(i) = ts.read(1)
i = i + 1
Wend
ts.close
readBinary = Join(a,"")
End Function
Sub writeBinary(bstr, path)
Dim fso
Dim ts
Set fso = CreateObject("Scripting.FileSystemObject")
On Error Resume Next
Set ts = fso.createTextFile(path)
If Err.number <> 0 Then
MsgBox(Err.message)
Exit Sub
End If
On Error GoTo 0
ts.Write(bstr)
ts.Close
End Sub
Function makeArray(n) ' Small utility function
Dim s
s = Space(n)
makeArray = Split(s," ")
End Function
The ADODB stream object is VBScript's only native method of reading binary streams. If ADODB is disabled, you will need to install some other third-party component to provide the same functionality.
It is possible to read all bytes together:
Set FS = CreateObject("Scripting.FileSystemObject")
Set fil = FS.GetFile(filename)
fpga = fil.OpenAsTextStream().Read(file.Size)
ADODB stream object is VBScript's only native method of reading binary streams
Const TypeBinary = 1
Const ForReading = 1, ForWriting = 2, ForAppending = 8
Function readBytes(file)
Dim inStream: Set inStream = WScript.CreateObject("ADODB.Stream") ' ADODB stream object used
inStream.Open ' open with no arguments makes the stream an empty container
inStream.type= TypeBinary
inStream.LoadFromFile(file)
readBytes = inStream.Read()
End Function
Sub writeBytes(file, bytes)
Dim binaryStream: Set binaryStream = CreateObject("ADODB.Stream")
binaryStream.Type = TypeBinary
binaryStream.Open 'Open the stream and write binary data
binaryStream.Write bytes
binaryStream.SaveToFile file, ForWriting 'Save binary data to disk
End Sub
Read 3 files & join to one file (without ADODB):
Dim oFSO : Set oFSO = CreateObject("Scripting.FileSystemObject")
If oFSO.FileExists("out.bin") Then oFSO.DeleteFile("out.bin")
Dim outFile : Set outFile = oFSO.OpenTextFile("out.bin", 8, true)
' 3 input files to concatenate
Dim oFS1 : Set oFS1 = oFSO.GetFile("in1.bin")
Dim oFS2 : Set oFS2 = oFSO.GetFile("in2.bin")
Dim oFS3 : Set oFS3 = oFSO.GetFile("in3.bin")
Dim read1 : Set read1 = oFS1.OpenAsTextStream()
Dim read2 : Set read2 = oFS2.OpenAsTextStream()
Dim read3 : Set read3 = oFS3.OpenAsTextStream()
Dim write1 : write1 = read1.Read(oFS1.Size)
read1.Close
outFile.write(write1)
Dim write2 : write2 = read2.Read(oFS2.Size)
read2.Close
outFile.write(write2)
Dim write3 : write3 = read3.Read(oFS3.Size)
read3.Close
outFile.write(write3)
outFile.Close
Tested on audio, video, image, zip archives & pdf (binaries) on Win 10 for binary file copy, edit, split, join, patching & (byte level) encryption, encoding & compression.
See example (answer) here for binary file patching.

Resources