Page 1 of 1

Reading file, line by line

Posted: Saturday 21st December 2019 2:13am
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

Re: Reading file, line by line

Posted: Saturday 21st December 2019 10:20am
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.

Re: Reading file, line by line

Posted: Saturday 21st December 2019 1:20pm
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.