Click to See Complete Forum and Search --> : Reading a file


Jean-Guy2000
April 23rd, 2001, 12:32 PM
HI, I am trying to use the API to read a entire file to a string, I need a fast way to open text and binary files. I write this function but it's crashing saying the memory cannot be written during the ReadFile DLL call. I know this is normally un-allocated buffer but I cannot seem to track the problem down, has anyone else done this? whats wrong with this code?

Public Function get_file_contents() As String
Dim fileContents As String
Dim lResult As Long
Dim lFileHandle As Long
Dim lTempFile As Long
Dim tSecurity As SECURITY_ATTRIBUTES
Dim tOverlapped As OVERLAPPED
Dim lFileSize As Long
Dim lBytesRead As Long

lFileHandle = CreateFile(FilePath, GENERIC_READ, 0, tSecurity, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, lTempFile)
If lFileHandle = INVALID_HANDLE_VALUE Then 'Did file open?
get_file_contents = "" 'Nope!
Exit Function 'we are done
End If
lResult = GetFileSize(lFileHandle, lFileSize) 'Get size of file
If lResult = INVALID_FILE_SIZE Then 'Did we get the size?
lResult = CloseHandle(lFileHandle) 'Close file handle
Exit Function 'Exit
End If
lFileSize = lResult 'Calc file size
fileContents = String(lFileSize, Chr(0)) 'allocate buffer
lResult = ReadFile(lFileHandle, fileContents, lFileSize, lBytesRead, tOverlapped)
lResult = CloseHandle(lFileHandle) 'Close filehandle
get_file_contents = fileContents
End Function

Jean-Guy

cksiow
April 23rd, 2001, 07:58 PM
I am not sure why you need to use API to read a entire file into a string variable, whereby VB can do it.

if u don't mind using VB code along, you can refer to http://vblib.virtualave.net, there is a function ReadFileStr in vbFileIO class which doing just what u want, reading entire file into a string variable.

HTH

Sharathms
April 24th, 2001, 03:00 AM
Hi, this code is there is in this forum already. this logic can read a ascii file,
but not sure about binary.
cheers,
Sharath

Dim strFileName as string
strFileName = "c:\temp\resy2000.log"
Dim strHuge as string
Dim LineCnt as Long
Dim ln as Long
Dim strFileContent() as string
Dim iFile as Integer
iFile = FreeFile
Open strFileName for input as #iFile
ln = FileLen(strFileName) 'get the lenth of the file
strHuge = Space(ln) 'Required
strHuge = input(ln, iFile) 'Read all the data into a string
Close #iFile 'close the file