How to read the entire text file in just one string in FB?

New to FreeBASIC? Post your questions here.
Post Reply
Herminio Gomes
Posts: 12
Joined: Dec 29, 2006 10:45

How to read the entire text file in just one string in FB?

Post by Herminio Gomes »

How to read the entire text file in just one string in FreeBasic?
The program below reads a line at once. I need to use the entire string in
the text file. How to do this ?

Code: Select all

Open Myfileinput For Input As #1
If Err>0 Then 
	Print "Error accessing file"
	Sleep 
  Else 
   Open Myfileoutput For Output As #2
   text=""
   While Not Eof(1)
	  Line Input #1,T
	  text=text+T+Chr(10)
   Wend  
   Print #2, text
Close 1
Close 2
MichaelW
Posts: 3500
Joined: May 16, 2006 22:34
Location: USA

Re: How to read the entire text file in just one string in F

Post by MichaelW »

One possiblity:

Code: Select all

dim as string buffer
open "filetostring.bas" for binary as 1
buffer = space(lof(1))
get #1,,buffer
print buffer
close
sleep
fxm
Moderator
Posts: 12556
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: How to read the entire text file in just one string in F

Post by fxm »

We can find also a similar example in FBWiki, with return value checked for functions 'Open' and 'Get'.
See the last example at:
GET # (File I/O)
Herminio Gomes
Posts: 12
Joined: Dec 29, 2006 10:45

Re: How to read the entire text file in just one string in F

Post by Herminio Gomes »

Works perfectly. Thanks a lot.
Herminio
codeFoil
Posts: 256
Joined: Dec 22, 2011 4:45
Location: United States
Contact:

Re: How to read the entire text file in just one string in F

Post by codeFoil »

Code: Select all

Var  fileNum = FreeFile

Open "TEST.TXT" for input as fileNum
Var  fileContent = Input(Lof(fileNum), fileNum)
Close fileNum

Print fileContent

Code: Select all

Function  FileContent(byref fileName as String) as String

    function = ""
    
    Var  fileNum = FreeFile
    If  Open(fileName, for input, as fileNum) = 0 Then
        function = Input(Lof(fileNum), fileNum)
        Close fileNum
    End  if

End  function

Print  FileContent("TEST.TXT")
Print  FileContent("TEST.BAS")
Post Reply