Page 1 of 1

Read file (specific line, specific line to EOF)

Posted: Mon Dec 05, 2022 10:46 am
by l1marik
For my purpose I need:
1, specific line from file (TXT) like:
readFileLine(file, line_number)

2, specific line from file (TXT) to EOF like:
readFileFrom(file, line_number)

Any ideas?

THX

Re: Read file (specific line, specific line to EOF)

Posted: Mon Dec 05, 2022 1:20 pm
by Allen
Hi,

I would suggest to read the whole file into memory (if you have enough RAM). Then use string function to get the required line(s)

Below is suggested code.

Code: Select all

EnableExplicit

Procedure Main()
  Protected.s InputFile$,FileContent$
  Protected.i InputF
  Protected.i LineNeeded,TotalLines,FromLineToEnd,i,TmpPos
  Protected.i Dim CRPos(1)
  
  InputFile$=OpenFileRequester("Select Input file", "C:\", "*.Txt", 0)
  InputF=OpenFile(#PB_Any,InputFile$,#PB_UTF8)
  FileContent$=ReadString(InputF,#PB_File_IgnoreEOL)
  
  TotalLines=CountString(FileContent$,#CRLF$)
  ReDim CRPos(TotalLines)
  
  ; scan and remember all CRLF position this will allow multiple access more quickly.
  CRPos(0)=0
  For i = 1 To TotalLines
    CRPos(i)=FindString(FileContent$,#CRLF$,CRPos(i-1)+1)
  Next  
  
  LineNeeded=2
  Debug Mid(FileContent$,CRPos(LineNeeded-1)+Len(#CRLF$),CRPos(LineNeeded)-CRPos(LineNeeded-1)-1)

  FromLineToEnd=4
  Debug Mid(FileContent$,CRPos(FromLineToEnd-1)+Len(#CRLF$))

EndProcedure

Main()
Allen

Re: Read file (specific line, specific line to EOF)

Posted: Mon Dec 05, 2022 1:34 pm
by NicTheQuick
Just use ReadString() to read the first n-1 lines and return the next line.

I don't think reading the whole file to memory and then using 'CountString()' and 'FindString()' are faster than that, because that means you have to evaluate the whole file even if you only want to read the second line. Also #CRLF is not always the end of line. It could also be just #LF like it is on most systems.

Re: Read file (specific line, specific line to EOF)

Posted: Wed Dec 07, 2022 1:36 pm
by l1marik
Solved:

Code: Select all

i = 0;
If ReadFile(0, "yourfile")          
  BOMformat = ReadStringFormat(0)     
  While Not Eof(0)
    line$ = ReadString(0)
    i = i + 1
    If (i = 2) ;only line 2 from yourfile
      Debug line$
    EndIf
    If (i > 4) ;from line nr 4 to end from yourfile
      Debug line$
    EndIf
  Wend
  CloseFile(0)
EndIf