Solved

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

Posted on 2007-12-04
4
738 Views
Last Modified: 2011-04-14
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 _
                             OF_SHARE_DENY_NONE)

             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 _
                             OF_SHARE_DENY_NONE)
            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)
         Else
             MsgBox "Not enough memory to store file"
         End If
      Else
         MsgBox "Input file is zero bytes in length"
      End If
      End

Open in new window

0
Comment
Question by:richelieu7777
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 
LVL 81

Accepted Solution

by:
zorvek (Kevin Jones) earned 500 total points
ID: 20404111
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

Kevin
0
 
LVL 17

Expert Comment

by:Shanmuga Sundaram
ID: 20404172
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
errfound:
MsgBox "Error " & Err.Description
End Sub

Private Sub Form_Load()
readandwritefile
End Sub
0
 
LVL 38

Expert Comment

by:PaulHews
ID: 20404203
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)
    Else
        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
errGetFile:
    Close
    MsgBox Err.Description, vbCritical, "GetFileContentBytes"
   
End Function
0
 
LVL 45

Expert Comment

by:aikimark
ID: 20411417
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)
Loop
'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.
0

Featured Post

Free Tool: ZipGrep

ZipGrep is a utility that can list and search zip (.war, .ear, .jar, etc) archives for text patterns, without the need to extract the archive's contents.

One of a set of tools we're offering as a way to say thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Most everyone who has done any programming in VB6 knows that you can do something in code like Debug.Print MyVar and that when the program runs from the IDE, the value of MyVar will be displayed in the Immediate Window. Less well known is Debug.Asse…
Enums (shorthand for ‘enumerations’) are not often used by programmers but they can be quite valuable when they are.  What are they? An Enum is just a type of variable like a string or an Integer, but in this case one that you create that contains…
As developers, we are not limited to the functions provided by the VBA language. In addition, we can call the functions that are part of the Windows operating system. These functions are part of the Windows API (Application Programming Interface). U…
Get people started with the process of using Access VBA to control Outlook using automation, Microsoft Access can control other applications. An example is the ability to programmatically talk to Microsoft Outlook. Using automation, an Access applic…

688 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question