Reading file, line by line

Post

Posted
Rating:
#1 (In Topic #352)
Regular
seany is in the usergroup ‘Regular’
Hi, Consider this snippet please:

Code (gambas)

  1.   Dim hFile As Stream
  2.   Dim sline As String
  3.   Dim linecntr As Integer
  4.  
  5.  hFile = Open FMain.appDefPath & FMain.projectPath & projectName & "/dtls.txt" For Input ' this opens
  6.  linecntr = 0
  7.  While Not Eof(hFile)
  8.      
  9.       Line Input #hFile, sline
  10.      
  11.       Print sline
  12.       Print Chr(13)
  13.       Print linecntr
  14.  
  15.      sline = ""
  16.      
  17.     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
Online now: No Back to the top

Post

Posted
Rating:
#2
Avatar
Guru
cogier is in the usergroup ‘Guru’
I would do this a different way.

Consider this code: -

Code (gambas)

  1. Public Sub Form_Open()
  2.  
  3.   Dim sArray As String[] = Split(File.Load(FMain.appDefPath &/ FMain.projectPath &/ projectName &/ "dtls.txt"), gb.Newline, "", True) ''NOTE THE USE OF THE /
  4.  
  5.   Print sArray.Join(gb.Newline)
  6.  
  7.  
Result: -
aaaaaaaa
bbbbbb
cccc
dd

This may be easier to understand: -

Code (gambas)

  1. Public Sub Form_Open()
  2.  
  3.   Dim sFile As String
  4.   Dim sArray As String[]
  5.   Dim sToUpLoad As String = FMain.appDefPath &/ FMain.projectPath &/ projectName &/ "dtls.txt"
  6.  
  7.   sFile = File.Load(sToUpLoad)
  8.   sArray = Split(sFile, gb.NewLine, "", True)
  9.  
  10.   Print sArray.Join(gb.Newline)
  11.  

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.
Online now: No Back to the top

Post

Posted
Rating:
#3
Avatar
Regular
stevedee is in the usergroup ‘Regular’

seany said


…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.
Online now: No Back to the top
1 guest and 0 members have just viewed this.