NaaLaa

Full Version: Uncorrectly read file
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Question
Case 1 : I think ... [for...next] is not the best way to read text file
Case 2 : I think this is the best way, but [do..until frln(f) = "unset"] gives unexpectedly output

Please advice me what is the best way to read the whole text file ?
Thank you.

Code:
set window "readfile",400,400

f = openfile("story.txt")

'Case 1
'correctly read file
for i = 0 to 21
    wln frln(f)
    i = i + 1
next

'Case 2
'uncorrectly read file
do
    wln frln(f)
until frln(f)="unset"

free file f

temp=rln()
Like this, maybe:

Code:
f = openfile("story.txt")
lin = frln(f)
while typeof(lin)
    pln lin
    lin = frln(f)
wend
free(f)

Or:

Code:
' contains a bunch of helper functions related to files.
include "file.n7"

' returns the lines of a text file as an array.
lines = ReadAllLines("story.txt")
for i = 0 to sizeof(lines) - 1  pln lines[i]

' return all text as a single string.
text = ReadAllText("story.txt")
pln text
Code:
text = system("type story.txt")
(03-23-2024, 02:28 PM)Tomaaz Wrote: [ -> ]
Code:
text = system("type story.txt")

Nice! I've never used that command Big Grin

And if you want to split it into an array of lines:

Code:
lines = split(system("type story.txt"), chr(10))
Thank you Tomaaz and Marcus for the solution.

Let me code it in this way :
Code:
'==================================
'Solutions (by Tomaaz and Marcus)
'use system type to read text file
'==================================

set window "read story.txt",400,400         

'chr(10) = ascii for \n, New Line
wln "File : Story.txt"
lines = split(system("type story.txt"), chr(10))
for k = 0 to sizeof(lines) - 1 wln lines[k]

wln
'put a space character in the beginning of an empty line (on the text file)
'so that every empty space line is written as it is.
wln "File : Story_.txt"
lines = split(system("type story_.txt"), chr(10))
for k = 0 to sizeof(lines) - 1 wln lines[k]

temp = rln()
Why not

Code:
wln system("type story.txt")

? It will print the entire file. What's the point of splitting?
comparison
using split() and without split() function

[attachment=163]
click the image to zoom in