Load data files

New to FreeBASIC? Post your questions here.
Post Reply
77jari
Posts: 6
Joined: Jun 28, 2022 23:14

Load data files

Post by 77jari »

Hi, can someone show the way i could make a code that loads data like this to print in the console

Code: Select all

jonh: 30
mary: 20
smith: 5
Laurens
Posts: 17
Joined: Mar 16, 2022 9:16
Location: Flevoland, the Netherlands

Re: Load data files

Post by Laurens »

Sure, I assume you got these data in a .txt file, for example: names.txt.

Code: Select all

Dim As Integer FileNumber
Dim As String Information

FileNumber = FreeFile

Open "names.txt" For Input As #FileNumber

Do Until (Eof (FileNumber) )
	Line input #1, Information
	Print lnformation
Loop

Close #FileNumber
dodicat
Posts: 7976
Joined: Jan 10, 2006 20:30
Location: Scotland

Re: Load data files

Post by dodicat »

Here are save and load text files.
I call your file simple.txt

Code: Select all

Sub savefile(filename As String,p As String)
    Dim As Long n=Freefile
    If Open (filename For Binary Access Write As #n)=0 Then
        Put #n,,p
        Close
    Else
        Print "Unable to save " + filename:Sleep:End
    End If
End Sub

Function loadfile(filename As String) As String
   Dim As Long  f=Freefile
   If Open (filename For Binary Access Read As #f)=0 Then
    Dim As String text
    If Lof(f) > 0 Then
      text = String(Lof(f), 0)
      Get #f, , text
    End If
    Close #f
    Return text
Else
  Print "Unable to load " + filename:Sleep:End 
  End If
End Function

Dim As String s=loadfile("simple.txt")
Print s


savefile("simple2.txt",s)

print loadfile("simple2.txt")
sleep
 
The text file (in entirety) will be loaded into a string
77jari
Posts: 6
Joined: Jun 28, 2022 23:14

Re: Load data files

Post by 77jari »

Thanks! but what i wanted to do is to make the program define variables for the numbers on the file.
fxm
Moderator
Posts: 12081
Joined: Apr 22, 2009 12:46
Location: Paris suburbs, FRANCE

Re: Load data files

Post by fxm »

By completing Laurens's code:

Code: Select all

Type Element
    Dim As String Label
    Dim As Double Value
End Type

Dim As Element List()
Dim As Integer FileNumber
Dim As String Information
Dim As Integer TagPosition

FileNumber = FreeFile

Open "names.txt" For Input As #FileNumber

Do Until (Eof (FileNumber) )
    Line input #1, Information
    TagPosition = Instr(Information, ":")
    If TagPosition > 0 Then
        Redim Preserve List(Ubound(List) + 1)
        List(Ubound(List)).Label = Left(Information, TagPosition - 1)
        List(Ubound(List)).Value = Val(Mid(Information, TagPosition + 1))
    End If
Loop

Close #FileNumber

For I As Integer = Lbound(List) To Ubound(List)
    Print List(I).Label, List(I).Value
Next I

Sleep
Post Reply