NaaLaa
Uncorrectly read file - Printable Version

+- NaaLaa (https://www.naalaa.com/forum)
+-- Forum: NaaLaa (https://www.naalaa.com/forum/forum-1.html)
+--- Forum: NaaLaa 7 Questions (https://www.naalaa.com/forum/forum-3.html)
+--- Thread: Uncorrectly read file (/thread-109.html)



Uncorrectly read file - 1micha.elok - 03-23-2024

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()



RE: Uncorrectly read file - Marcus - 03-23-2024

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



RE: Uncorrectly read file - Tomaaz - 03-23-2024

Code:
text = system("type story.txt")



RE: Uncorrectly read file - Marcus - 03-23-2024

(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))



RE: Uncorrectly read file - 1micha.elok - 03-24-2024

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()



RE: Uncorrectly read file - Tomaaz - 03-24-2024

Why not

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

? It will print the entire file. What's the point of splitting?


RE: Uncorrectly read file - 1micha.elok - 03-24-2024

comparison
using split() and without split() function

   
click the image to zoom in