Support Forums > General Board

how to read an entire text file into a string?

(1/2) > >>

ChrisC:
Hello all

can someone please give me some code to read an entire text file into a string?

and what kind of string shall i use ?  WSTRING or ordinary string

thanks a lot

Pierre Bellisle:
Try this...


--- Code: ---'_____________________________________________________________________________

FUNCTION FileDataGet(BYVAL sFileName AS STRING, BYREF sFileData AS STRING) AS UINT32
 Dim hFile        AS HWND
 Dim FileSizeLo   AS DWORD
 Dim FileSizeHi   AS DWORD
 Dim ReturnCount  AS DWORD

 sFileData = ""
 hFile = CreateFileA(Cast(LPCSTR, STRPTR(sFileName)), GENERIC_READ, FILE_SHARE_READ, _
                     BYVAL 0, OPEN_EXISTING, FILE_ATTRIBUTE_NORMAL, 0)
 IF hFile <> INVALID_HANDLE_VALUE THEN
   FileSizeLo = GetFileSize(hFile, @FileSizeHi)
   sFileData  = String(FileSizeLo, 0)
   ReadFile(hFile, Cast(LPVOID, STRPTR(sFileData)), FileSizeLo, @ReturnCount, BYVAL 0)
   CloseHandle(hFile)
   IF ReturnCount = FileSizeLo THEN
     FUNCTION = ReturnCount
   END IF
 END IF

END FUNCTION
'_____________________________________________________________________________

FUNCTION FileDataSet(BYVAL sFileName AS STRING, BYREF sFileData AS STRING) AS UINT32
 Dim hFile        AS HWND
 Dim WrittenCount AS DWORD

 hFile = CreateFileA(Cast(LPCSTR, STRPTR(sFileName)), GENERIC_READ OR GENERIC_WRITE, _
                     FILE_SHARE_READ, BYVAL 0, CREATE_ALWAYS, FILE_ATTRIBUTE_NORMAL, 0)
 IF hFile <> INVALID_HANDLE_VALUE THEN
   WriteFile(hFile, Cast(LPCSTR, STRPTR(sFileData)), LEN(sFileData), @WrittenCount, BYVAL 0)
   SetEndOfFile(hFile)
   CloseHandle(hFile)
   IF WrittenCount = LEN(sFileData) THEN
     FUNCTION = WrittenCount
   END IF
 END IF

END FUNCTION
'_____________________________________________________________________________
'

--- End code ---

Josť Roca:
What kind of string you have to use depends on if the contents of the file are ansi or unicode.

Jim Dunn:
(and don't forget about processing line-endings (CR or LF or CRLF))

I usually do something like this:


--- Code: ---    fpIN = FREEFILE
    OPEN sfilename FOR BINARY AS #fpIN
    IF ERR THEN
        STDERR "File [" & sfilename & "] could not be opened."
        EXIT FUNCTION
    END IF
    GET$ #fpIN, LOF(#fpIN), a
    CLOSE #fpIN

    REPLACE $CRLF WITH $CR IN a ' for Windows line-endings
    REPLACE $LF   WITH $CR IN a ' for Linux line-endings
    REPLACE $CR   WITH $CRLF IN a ' for Mac line-endings
--- End code ---

Sorry it's "PowerBASIC"... haven't moved to FreeBasic yet...

Johan Klassen:
here are some ways https://www.freebasic.net/forum/viewtopic.php?p=243407

Navigation

[0] Message Index

[#] Next page

Go to full version