Reading file, line by line

Post your Gambas programming questions here.
Post Reply
seany
Posts: 32
Joined: Friday 6th December 2019 3:09pm

Reading file, line by line

Post by seany »

Hi, Consider this snippet please:
  Dim hFile As Stream
  Dim sline As String
  Dim linecntr As Integer
  
 hFile = Open FMain.appDefPath & FMain.projectPath & projectName & "/dtls.txt" For Input ' this opens
 linecntr = 0 
 While Not Eof(hFile) 
      
      Line Input #hFile, sline
      
      Print sline
      Print Chr(13)
      Print linecntr

     sline = ""
      
    Wend

This file contains this data:

aaaaaaaa
bbbbbb
cccc
dd

And the result that I am getting is :
ddccbbaa

That means, that the line input command is reading all the lines one by one, and storing them in the same variable, without executing the next instructions in the while loop.

Why is this? What am I doing wrong?

Gambas 3.14.2 pi
User avatar
cogier
Site Admin
Posts: 1118
Joined: Wednesday 21st September 2016 2:22pm
Location: Guernsey, Channel Islands

Re: Reading file, line by line

Post by cogier »

I would do this a different way.

Consider this code: -
Public Sub Form_Open()

  Dim sArray As String[] = Split(File.Load(FMain.appDefPath &/ FMain.projectPath &/ projectName &/ "dtls.txt"), gb.Newline, "", True) ''NOTE THE USE OF THE /

  Print sArray.Join(gb.Newline)

End
Result: -
aaaaaaaa
bbbbbb
cccc
dd

This may be easier to understand: -
Public Sub Form_Open()

  Dim sFile As String
  Dim sArray As String[]
  Dim sToUpLoad As String = FMain.appDefPath &/ FMain.projectPath &/ projectName &/ "dtls.txt"

  sFile = File.Load(sToUpLoad)
  sArray = Split(sFile, gb.NewLine, "", True)

  Print sArray.Join(gb.Newline)

End
Have a look at the Split command here, Join command http://gambaswiki.org/wiki/comp/gb/string[]/join
String &/ String Concatenate two strings that contain file names. Add a path separator between the two strings if necessary.
User avatar
stevedee
Posts: 518
Joined: Monday 20th March 2017 6:06pm

Re: Reading file, line by line

Post by stevedee »

seany wrote: Saturday 21st December 2019 2:13am
...And the result that I am getting is :
ddccbbaa

That means, that the line input command is reading all the lines one by one, and storing them in the same variable, without executing the next instructions in the while loop.

Why is this? What am I doing wrong?
Its because you are using a carriage return (decimal 13) instead of a line feed (decimal 10).

Windows likes CR + LF but Linux likes just LF.
Post Reply