Read file (specific line, specific line to EOF)

Just starting out? Need help? Post your questions and find answers here.
l1marik
User
User
Posts: 49
Joined: Tue Jun 30, 2020 6:22 am

Read file (specific line, specific line to EOF)

Post 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
Allen
User
User
Posts: 92
Joined: Wed Nov 10, 2021 2:05 am

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

Post 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
User avatar
NicTheQuick
Addict
Addict
Posts: 1224
Joined: Sun Jun 22, 2003 7:43 pm
Location: Germany, Saarbrücken
Contact:

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

Post 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.
The english grammar is freeware, you can use it freely - But it's not Open Source, i.e. you can not change it or publish it in altered way.
l1marik
User
User
Posts: 49
Joined: Tue Jun 30, 2020 6:22 am

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

Post 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
Post Reply