Want to protect your cyber security and still get fast solutions? Ask a secure question today.Go Premium

  • Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 763
  • Last Modified:

How to Read the contents of an entire file into memory and be able to READ it

I have a need to quickly read the contents of a file into memory using VB6.  I know how to do this in VB.NET via BinaryReader functionality; however, I need to do this within VB6.

I have used the following code that can read the data from a file into memory, but I don't know know how to *access* it:

hMem = GlobalAlloc(GPTR, FSize)
If hMem <> 0 Then
            lpMem = GlobalLock(hMem)
            hFile = OpenFile(InpFile, fileStruct, OF_READ Or _

             BytesRead = hread(hFile, ByVal lpMem, FSize)

That's fine and dandy, but how do I parse the data in memory location lpMem into a string array?  i.e. in C one might say:

char x[100000]
x[1] = lpMem + 1

but how do you do this in VB6?????

I've attached a code snippet of some sample code I found on the net.

Thanks in advance for your help
Dim InpFile As String
      Dim OutFile As String
      Dim hFile As Long
      Dim fileStruct As OFSTRUCT
      Dim FSize As Long
      Dim BytesRead As Long
      Dim BytesWritten As Long
      Dim hMem As Long
      Dim lpMem As Long
      Dim r As Long
      Dim bts As Byte
      InpFile = "input.txt"
      OutFile = "OUTPUT.txt"
      'Get the size of the file to be read
      FSize = FileLen(InpFile)
      If FSize > 0 Then
         'Allocate a block of memory equal to the size of the input file.
         'hMem = GlobalAlloc(GMEM_ZEROINIT, FSize)
         hMem = GlobalAlloc(GPTR, FSize)
         If hMem <> 0 Then
            lpMem = GlobalLock(hMem)
            'Read the file into memory
            hFile = OpenFile(InpFile, fileStruct, OF_READ Or _
            BytesRead = hread(hFile, ByVal lpMem, FSize)
            MsgBox Format(BytesRead) & " bytes read into memory"
            r = lclose(hFile)
            'Write the file back to disk to verify the file was
            'read correctly
            hFile = OpenFile(OutFile, fileStruct, OF_CREATE Or _
                             OF_WRITE Or OF_SHARE_DENY_NONE)
            BytesWritten = hwrite(hFile, ByVal lpMem, FSize)
            MsgBox Format(BytesWritten) & " bytes written to output file"
            r = lclose(hFile)
            'Free resources
            r = GlobalUnlock(hMem)
            r = GlobalFree(hMem)
             MsgBox "Not enough memory to store file"
         End If
         MsgBox "Input file is zero bytes in length"
      End If

Open in new window

1 Solution
zorvek (Kevin Jones)ConsultantCommented:
The sample code below illustrates how to use the Visual Basic file system to read an entire file into a string variable.

   Dim FilePath As String
   Dim FileNumber As Long
   Dim FileData As String

   FilePath = "C:\Full\Path\To\File.txt"
   FileNumber = FreeFile
   Open FilePath For Binary Access Read As FileNumber
   ' Use following if non-unicode data
   FileData = StrConv(InputB(LOF(FileNumber), FileNumber), vbUnicode)
   ' Use following if unicode data
   'FileData = InputB(LOF(FileNumber), FileNumber)
   Close FileNumber

Shanmuga SundaramDirector of Software EngineeringCommented:
if you want to read and write text file please check this

Private Sub readandwritefile()
On Error GoTo errfound
Dim InpFile As String
      Dim OutFile As String
      InpFile = "c:input.txt"
      OutFile = "c:\OUTPUT.txt"
Dim filecontent As String
Open InpFile For Input As #1
filecontent = Input$(LOF(1), 1)
Close #1
Open OutFile For Output As #2
Print #2, filecontent
Close #2
Exit Sub
MsgBox "Error " & Err.Description
End Sub

Private Sub Form_Load()
End Sub
Function that returns a byte array, given the path:

Public Function fGetFileContentBytes(strPath As String) As Byte()
    Dim hFile As Integer
    Dim bytFileContent() As Byte
    If Len(Dir(strPath)) = 0 Then Exit Function
    On Error GoTo errGetFile
    'Handle zero length files
    If FileLen(strPath) = 0 Then
        ReDim bytFileContent(-1 To -1)
        hFile = FreeFile
        Open strPath For Binary As #hFile
        ReDim bytFileContent(1 To LOF(hFile))
        Get #hFile, , bytFileContent
        Close #hFile
    End If
    fGetFileContentBytes = bytFileContent
    Exit Function
    MsgBox Err.Description, vbCritical, "GetFileContentBytes"
End Function
Dim strFilePath As String
Dim intFN As Integer
Dim strFileData As String
Dim colFileData As New Collection
Dim lngEOL_Posn As Long
Dim lngSOL_Posn As Long

strFilePath = "C:\Full\Path\To\File.txt"
intFN = FreeFile
Open FilePath For Input As intFN
strFileData = Input(LOF(intFN), intFN)
Close intFN
'parse the data
lngSOL_Posn = 1
lngEOL_Posn = InStr(lngSOL_Posn, strFileData, vbCrLf)
Do Until lngEOL_Posn = 0
  colFileData.Add Mid$(strFileData, lngSOL_Posn, lngEOL_Posn - lngSOL_Posn)
  lngSOL_Posn = lngEOL_Posn +2
  lngEOL_Posn = InStr(lngSOL_Posn, strFileData, vbCrLf)
'Add the last segment
If lngSOL_Posn < Len(strFileData) Then _
colFileData.Add Mid$(strFileData, lngSOL_Posn)
strFileData = vbNullString

At this point, each line of the file is an item in the collection.  You can reference the collection items numerically, just as you would a string array.

Featured Post

[Webinar] Database Backup and Recovery

Does your company store data on premises, off site, in the cloud, or a combination of these? If you answered “yes”, you need a data backup recovery plan that fits each and every platform. Watch now as as Percona teaches us how to build agile data backup recovery plan.

Tackle projects and never again get stuck behind a technical roadblock.
Join Now