Author Topic: How to read a text file into a string array  (Read 282 times)

0 Members and 1 Guest are viewing this topic.

Offline Chris Chancellor

  • Sr. Member
  • ****
  • Posts: 316
How to read a text file into a string array
« on: January 11, 2019, 03:07:53 AM »
Hello Charles

i have the  text file below which i need to read into a string array   ArStr[ ] 

how do i write the program to read this file with each line entry is demakated by a carriage return ?

Code: [Select]
lin1                                   
lin2 rwerwe5rt34                       
lin3  mnner erert                       
lin4  jldjl g                           
lin5  fhrtu 5 56543                     
lin6   jre4t 34@45                     
This is Line 7                                 
 O2 in Line 8                                       
lin9   rtyrek trtr                     
lin10                     


so that string array elements are
  ArStr[1]  = "lin1"
  ArStr[1]  = "lin2 rwerwe5rt34"

and so on
« Last Edit: January 11, 2019, 03:12:00 AM by Chris Chancellor »

Offline Charles Pegge

  • Global Moderator
  • Hero Member
  • *****
  • Posts: 684
    • Charles Pegge
Re: How to read a text file into a string array
« Reply #1 on: January 11, 2019, 07:05:18 AM »
Hi Chris,

This is a slightly modified version of examples\DataProcessing\LineSplitter1.o2bas

Code: [Select]

'=============
'LINE SPLITTER
'=============

indexbase 1
string lines[100000] 'static lines array
string cr             '
int b,i,j            '


'data:
'=====

'txt=getfile "s.txt"

'txt=nuls 100000
'sendMessage richedit1,WM_GETTEXT,100000, strptr txt
'
string txt="11
22
33
44
55
66

77"

'initial
'=======
'
'
b=1  'start of line
i=0  'lines array index
j=1  'char index
'
'
'splitter loop
'=============
'
do
  select asc(txt,j)
  case 0
    if j-b>0 then
      i++
      lines[i]=mid(txt,b,j-b) 'FINAL LINE
    end if
    exit do
  case 10 'LF TERMINATED LINES
    i++
    lines[i]=mid(txt,b,j-b)
    b=j+1
  case 13 'CR AND CRLF TERMINATED LINES
    i++
    lines[i]=mid(txt,b,j-b)
    if asc(txt,j+1)=10 then j++ 'SKIP LF
    b=j+1
  end select
  j++   
end do


cr=chr(13)+chr(10)
print "Lines:  " i cr +
      "Line 5: " lines[5] + cr +
      "Last:   " lines[i]

Offline Chris Chancellor

  • Sr. Member
  • ****
  • Posts: 316
Re: How to read a text file into a string array
« Reply #2 on: January 11, 2019, 02:49:15 PM »
Thanxx a lot , Charles

This is exactly what i wanted,  thanxx for your invaluable time,  you really made O2 a great language