I am trying to make a project that can allows me to read from a specific file as binary and from an specific offset in the file.
I found the following code without the main souce:
Sub GetData()
Dim nFileNum As Integer, sLocation1 As String, sLocation2 As String 'declarations
nFileNum = FreeFile 'get file ID
Open App.Path & "\Hologram.bin" For Binary Access Read Lock Read Write As #nFileNum 'file to open
sLocation1 = Space$(10) 'my first offset is 10 chars long, set a string placeholder must equal the size of data you want to hold
sLocation2 = Space$(32) 'my second offset is 32 chars longs, set a string placeholder must equal the size of data you want to hold
Get #nFileNum, 12000, sLocation1 'The offset location in Binary of the data I want to show (+1 to offset because we start at 0!)
Text1.Text = sLocation1 'display the 10 chars data in a textbox
Get #nFileNum, 12500, sLoation2 ' The offset location in Binary of the data I want to show (+1 to offset because we start at 0!)
Text2.Text = sLocation2 'display the 32 chars data in a textbox
Close #nFileNum 'Cloase the file
End Sub 'Call GetData()
Sub WriteBin()
Dim sFileText As String 'declarations
Dim iFileNo As Integer
iFileNo = FreeFile
Dim nFileNum As Integer
nFileNum = FreeFile 'get random file number
Open App.Path & "filename.bin" For Binary Access Write Lock Read Write As #nFileNum 'open file for edit
Put #nFileNum, 12000, Text1.Text 'Offset is +1 because we start at 0! write data from textbox1 to offset location
Put #nFileNum, 12500, Text2.Text 'Offset is +1 because we start at 0! write data from textbox2 to offset location
Close #nFileNum 'Call WriteBin()
End Sub
I would like to find the rest of this code so I can use it.
Thanks
Related
I am making a number generator for my own purpose.
I already made it to work with these features:
- Saves the generated number
What features I want :
- When I close it loads the last generated number from the notepad.
here is the code:
Private Const FilePath As String = "C:\Users\sto0007404\Documents\Numbers.txt"
Private CurrentNumber As Long
Private Sub Command1_Click()
CurrentNumber = CurrentNumber + 1
txtRefNo.Text = "EM" & Format(CurrentNumber, String(4, "0"))
End Sub
Private Sub Form_Load()
Dim TextFileData As String, MyArray() As String, i As Long
' Open file as binary
Open "FilePath" For Binary As #1
' Read entire file's data in one go
TextFileData = Space$(LOF(1))
Get #1, , TextFileData
' Close File
Close #1
' Split the data in separate lines
MyArray() = Split(TextFileData, vbCrLf)
For i = 0 To UBound(MyArray())
' Set CurrentNumber equal to the current max
CurrentNumber = Val(Mid$(MyArray(i), 2))
Next
End Sub
Private Sub Form_QueryUnload(Cancel As Integer, UnloadMode As Integer)
Dim i As Long
' delete the old file
If Not LenB(Dir(FilePath)) = 0 Then Kill FilePath
'open the file for writing
Open FilePath For Output As #1
For i = 1 To CurrentNumber
Write #1, "EM" & Format(i, String(4, "0"))
Next
'close the file (if you dont do this, you wont be able to open it again!)
Close #1
End Sub
Independent of use binary mode...
open file for output as #1
print #1, "Some text"
close #1
open file for input as #1
line input #1, myvariable
close #1
msgbox myvariable
The flow is the same that you show, so what is the problem ?
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
>>
I know how to do it in VB.Net but not an idea in vb6.
What I what to achieve is to avoid reading the whole file.
Is that possible?
You could open the file using Random access. Work your way backward a byte at a time, counting the number of carriage return line feed character pairs. Store each line in an array, or something similar, and when you've read your 400 lines, stop.
Cometbill has a good answer.
To open file for Random access:
Open filename For Random Access Read As #filenumber Len = reclength
To get the length of the file in Bytes:
FileLen(ByVal PathName As String) As Long
To read from Random access file:
Get [#]filenumber,<[recnumber]>,<varname>
IMPORTANT: the <varname> from the Get function must be a fixed length string Dim varname as String * 1, otherwise it will error out with Bad record length (Error 59) if the variable is declared as a variable length string like this Dim varname as String
EDIT:
Just wanted to point out that in Dim varname as String * 1 you are defining a fixed length string and the length is 1. This is if you wish to use the read-1-byte-backwards approach. If your file has fixed length records, there is no need to go 1 byte at a time, you can read a record at a time (don't forget to add 2 bytes for carriage return and new line feed). In the latter case, you would define Dim varname as String * X where X is the record length + 2. Then a simple loop going backwards 400 times or untill reaching the beginning of the file.
The following is my take on this. This is more efficient than the previous two answers if you have a very large file, since we don't have to store the entire file in memory.
Option Explicit
Private Sub Command_Click()
Dim asLines() As String
asLines() = LoadLastLinesInFile("C:\Program Files (x86)\VMware\VMware Workstation\open_source_licenses.txt", 400)
End Sub
Private Function LoadLastLinesInFile(ByRef the_sFileName As String, ByVal the_nLineCount As Long) As String()
Dim nFileNo As Integer
Dim asLines() As String
Dim asLinesCopy() As String
Dim bBufferWrapped As Boolean
Dim nLineNo As Long
Dim nLastLineNo As Long
Dim nNewLineNo As Long
Dim nErrNumber As Long
Dim sErrSource As String
Dim sErrDescription As String
On Error GoTo ErrorHandler
nFileNo = FreeFile
Open the_sFileName For Input As #nFileNo
On Error GoTo ErrorHandler_FileOpened
' Size our buffer to the number of specified lines.
ReDim asLines(0 To the_nLineCount - 1)
nLineNo = 0
' Read all lines until the end of the file.
Do Until EOF(nFileNo)
Line Input #nFileNo, asLines(nLineNo)
nLineNo = nLineNo + 1
' Check to see whether we have got to the end of the string array.
If nLineNo = the_nLineCount Then
' In which case, flag that we did so, and wrap back to the beginning.
bBufferWrapped = True
nLineNo = 0
End If
Loop
Close nFileNo
On Error GoTo ErrorHandler
' Were there more lines than we had array space?
If bBufferWrapped Then
' Create a new string array, and copy the bottom section of the previous array into it, followed
' by the top of the previous array.
ReDim asLinesCopy(0 To the_nLineCount - 1)
nLastLineNo = nLineNo
nNewLineNo = 0
For nLineNo = nLastLineNo + 1 To the_nLineCount - 1
asLinesCopy(nNewLineNo) = asLines(nLineNo)
nNewLineNo = nNewLineNo + 1
Next nLineNo
For nLineNo = 0 To nLastLineNo
asLinesCopy(nNewLineNo) = asLines(nLineNo)
nNewLineNo = nNewLineNo + 1
Next nLineNo
' Return the new array.
LoadLastLinesInFile = asLinesCopy()
Else
' Simply resize down the array, and return it.
ReDim Preserve asLines(0 To nLineNo)
LoadLastLinesInFile = asLines()
End If
Exit Function
ErrorHandler_FileOpened:
' If an error occurred whilst reading the file, we must ensure that the file is closed
' before reraising the error. We have to backup and restore the error object.
nErrNumber = Err.Number
sErrSource = Err.Source
sErrDescription = Err.Description
Close #nFileNo
Err.Raise nErrNumber, sErrSource, sErrDescription
ErrorHandler:
Err.Raise Err.Number, Err.Source, Err.Description
End Function
So I have a number of text files that I'm trying to read with Visual Basic. They all have the same formatting:
[number of items in the file]
item 1
item 2
item 3
...etc.
What I'm trying to do is declare an array of the size of the integer in the first line, and then read each line into corresponding parts of the array (so item 1 would be array[0], item 2 would be array[1], etc. However, I'm not sure where to start on this. Any help would be appreciated.
Pretty basic stuff (no pun intended):
Dim F As Integer
Dim Count As Integer
Dim Items() As String
Dim I As Integer
F = FreeFile(0)
Open "data.txt" For Input As #F
Input #F, Count
ReDim Items(Count - 1)
For I = 0 To Count - 1
Line Input #F, Items(I)
Next
Close #F
try this for VB6
Dim file_id As Integer
Dim strline as string
Dim array_item() as string
'Open file
file_id = FreeFile
Open "C:\list.txt" For Input AS #file_id
Dim irow As Integer
irow = 0
'Loop through the file
Do Until EOF(file_id)
'read a line from a file
Line Input #file_id, strline
'Resize the array according to the line read from file
Redim Preserve array_item(irow)
'put the line into the array
array_item(irow) = strline
'move to the next row
irow = irow + 1
Loop
Close #file_id
The VB function you're looking for is "split":
http://www.vb-helper.com/howto_csv_to_array.html
Try this:
Dim FullText As String, l() As String
'''Open file for reading using Scripting Runtime. But you can use your methods
Dim FSO As Object, TS As Object
Set FSO = createbject("Scripting.FileSystemObject")
Set TS = createbject("Scripting.TextStream")
Set TS = FSO.OpenTextFile(FilePath)
TS.ReadLine 'Skip your first line. It isn't needed now.
'''Reading the contents to FullText and splitting to the array.
FullText = TS.ReadAll
l = Split(FullText, vbNewLine) '''the main trick
Splitting automatically resizes l() and stores all data.
Now the l() array has everything you want.
The following VB 6 code saves text from the textBox in the form GUI to file.txt (By the click on the button)
How to do the reverse option – copy/capture file text (file.txt) , and passed it on the textBox in the form GUI , I will happy to get real example
remark - (before passed need to clear the form window from any text )
Private Sub save_Click()
saves = (Form1.Caption)
FCO.CreateTextFile App.Path & "\" & saveas & "file.txt", True
FCO.OpenTextFile(App.Path & "\" & saveas & "file.txt", ForWriting).Write Text1.Text
End Sub
This reads from a file and puts the results in Text1.Text.
Private Sub save_Click()
Dim sFile as String
sFile = "c:\whatever"
Dim sData as String
Dim fnum as Integer
fnum = FreeFile()
Open sFile For Input As #fnum
If Not eof(fnum) Then
Input #fnum, sData
Text1.Text= sData
End If
Close #fnum
End Sub
You can load in the contents of a file using the standard VB6 file I/O operations
Dim FileNum As Integer
Dim Size As Long
Dim Data() As Byte
'Open the file
FileNum = FreeFile()
Open FileName For Binary As #FileNum
'Read all the data
Size = LOF(FileNum)
ReDim Data(Size - 1)
Get #FileNum, , Data
Close #FileNum
'Convert to a string
TextBox.Text = StrConv(Data, vbUnicode)
See the original article.