How to resolve the algorithm Read a file line by line step by step in the BASIC programming language

Published on 12 May 2024 09:40 PM

How to resolve the algorithm Read a file line by line step by step in the BASIC programming language

Table of Contents

Problem Statement

Read a file one line at a time, as opposed to reading the entire file at once.

Let's start with the solution:

Step by Step solution about How to resolve the algorithm Read a file line by line step by step in the BASIC programming language

Source code in the basic programming language

' Read a file line by line
filename$ = "readlines.bac"
OPEN filename$ FOR READING AS fh
READLN fl$ FROM fh
WHILE ISFALSE(ENDFILE(fh))
    INCR lines
    READLN fl$ FROM fh 
WEND
PRINT lines, " lines in ", filename$
CLOSE FILE fh

100 INPUT PROMPT "Filename: ":NAME$
110 OPEN #1:NAME$ ACCESS INPUT
120 COPY FROM #1 TO #0
130 CLOSE #1

10 OPENIN"foo.txt"
20 WHILE NOT EOF
30 LINE INPUT#9,i$
40 PRINT i$
50 WEND

function getline(string s, int *i) as string
  int sl=i, el=i
  byte b at strptr(s)
  do
    select b[el]
      case 0
        i=el+1 : exit do
      case 10 'lf
        i=el+1 : exit do
      case 13 'cr
        i=el+1
        if b[i]=10 then i++ 'crlf
        exit do
    end select
    el++
  loop
  return mid(s,sl,el-sl)
end function
 
'read all file lines
'===================
 
string s=getfile "t.txt"
int le=len(s)
int i=1
int c=0
string wr
if le=0 then goto done
do 
  wr = getline(s,i)
  'print wr
  c++
  if i>le then exit do
end do
done:
print "Line count " c

f = FREEFILE
filename$ = "file.txt"
           
OPEN filename$ FOR INPUT AS #f

WHILE NOT EOF(f)
    LINE INPUT #f, linea$
    PRINT linea$
WEND
CLOSE #f
END


If Set (a, Open ("myfile.bas", "r")) < 0 Then Print "Cannot open \qmyfile.bas\q" : End

Do While Read (a)
  Print Show(Tok(0))
Loop

Close a


10 REM open my file for input
20 OPEN #4;"m";1;"MYFILE": REM stream 4 is the first available for general purpose
30 INPUT #4; LINE a$: REM a$ will hold our line from the file
40 REM because we do not know how many lines are in the file, we need an error trap
50 REM to gracefully exit when the file is read. (omitted from this example)
60 REM to prevent an error at end of file, place a handler here
100 GOTO 30


  

You may also check:How to resolve the algorithm Arithmetic/Integer step by step in the Chef programming language
You may also check:How to resolve the algorithm Matrix multiplication step by step in the D programming language
You may also check:How to resolve the algorithm Spelling of ordinal numbers step by step in the REXX programming language
You may also check:How to resolve the algorithm Strip comments from a string step by step in the Rust programming language
You may also check:How to resolve the algorithm Modular arithmetic step by step in the D programming language