Friday, October 12, 2018

Reading a Text File line by line in FoxPro



For reading a text file in VFP, you have more than one ways..


Method 1. Visual FoxPro has a set of low-level file functions that are ideal for this and other purposes when working with files. Assuming each line in the text file is terminated with a carriage return, you can use FGETS to read the file line by line. Here is a sample program to illustrate:

LOCAL lnFileHandle && numeric file handle
lnFileHandle = FOPEN( "myTextFile.txt")
IF lnFileHandle = -1
   && error, could not open the file
   && do something to handle the error
   RETURN
ENDIF
LOCAL lcLine && define a variable to hold each line
DO WHILE NOT FEOF( lnFileHandle) && loop through the file
   lcLine = FGETS( lnFileHandle) && store each line in lcLine
   ?lcLine && do something with the line, such as display it
ENDDO
FCLOSE( lnFileHandle) && don't forget to close the file

RETURN && done
}

Method 2. You can append the textfile into a table/cursor and loop it through.

SET TALK OFF
CLEAR ALL
CLEAR
CREATE CURSOR temp (LINE C(200))
APPEN FROM GETF('TXT') SDF
GO TOP
DO WHILE !EOF()
? LINE
SKIP
ENDDO
CLOSE DATABASES
SET TALK ON
RETURN
}

Method 3. You can use the filetostr(). It'll take the entire file to a memory variable, which you can parse  through.

local ix
local array aParse[1]
for ix = 1 to ALines( aParse, FileToStr("myFile.txt"))
    ? AParse[m.ix]  && AParse[m.ix] contains current line in loop - do whatever with it
endfor

}
Alines() reads a string and parses it into lines (you can supply delimiter so instead of parsing lines you may be parsing say a comma separated string into lines - like Split() ). Default delimiter is CR, LF or CRLF.
Return value is the total number of lines and the array created is a single dimension array. To get a file as a string you can use FileToStr("myFile.txt"). Arrays in VFP are 1 based, unlike Java or C where first element's index is 0.


No comments:

Post a Comment