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
Solved

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

Posted on 2007-12-04
4
734 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
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: Postgres Monitoring System

A PHP and Perl based system to collect and display usage statistics from PostgreSQL databases.

One of a set of tools we are providing to everyone as a way of saying 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

Suggested Solutions

Title # Comments Views Activity
Computer crashes, following error message in event manager 5 236
using Access 8 75
VB 6 error 5 in windows 10 but not in XP 7 63
RUNRMTCMD from AS/400 12 68
When trying to find the cause of a problem in VBA or VB6 it's often valuable to know what procedures were executed prior to the error. You can use the Call Stack for that but it is often inadequate because it may show procedures you aren't intereste…
If you have ever used Microsoft Word then you know that it has a good spell checker and it may have occurred to you that the ability to check spelling might be a nice piece of functionality to add to certain applications of yours. Well the code that…
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…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…

856 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