One little thing to watch out for...
Sometimes 'text' files END with a CRLF, sometimes they don't.
Announcement
Collapse
No announcement yet.
Last record in a sequential file
Collapse
X
-
If a file is very large this could prevent having to read it all.
Code:#COMPILE EXE #DIM ALL DECLARE FUNCTION GetLastRecordSequential(sFile AS STRING) AS STRING FUNCTION PBMAIN AS LONG 'Create a sequential file and get last record LOCAL sFile AS STRING LOCAL h AS LONG LOCAL s AS STRING LOCAL x AS LONG sFile = "c:\test.txt" h = FREEFILE OPEN sFile FOR OUTPUT AS #h PRINT #h, "Record 1" PRINT #h, "Record 2 here" PRINT #h, "Record 3 is the last record in the file" CLOSE #h ? $DQ + GetLastRecordSequential(sFile) + $DQ SLEEP 3000 END FUNCTION FUNCTION GetLastRecordSequential(sFile AS STRING) AS STRING LOCAL x AS LONG LOCAL s AS STRING LOCAL h AS LONG h = FREEFILE OPEN sFile FOR BINARY AS #h IF LOF(h) = 0 THEN CLOSE #h BEEP EXIT FUNCTION END IF s = " " FOR x = LOF(h)-1 TO 1 STEP -1 GET #h, x, s IF ASC(s) = 10 THEN 'search for previous line feed s = SPACE$(LOF(h)-x-2) GET #h, x+1,s EXIT FOR END IF NEXT IF x = 0 THEN 'no line feed found, entire file is last record s = SPACE$(LOF(h)-2) GET #h, 1, s END IF CLOSE #h FUNCTION = s END FUNCTION
Leave a comment:
-
Much faster to read it all in and then look for the record you want anyways.
Less read, writes, and case in point, try reading it all from a floppy vs on your hard-drive....you will see phenomenal speed differences
Leave a comment:
-
> think it will have to be filescan and read the file
If all you want is the last record, it does not have to be that, as pointed out above
But if you don't feel like doing that little bit, there's no need to FILESCAN:
Code:hin = FREEFILE OPEN "thefile" for INPUT AS hIN WHILE NOT EOF(hIn) LINE INPUT#hIn, S WEND ' when you get here, 'S' is the last sequential record. CLOSE hin
Leave a comment:
-
Or, for a text file, you can open it in binary mode, and start reading backward blocks of bytes (for example, 16KB), until you find a $CRLF in it.
Bye!
Leave a comment:
-
Do you mean for RANDOM file access? If so, a simple calculation can be used to get the record count:
Code:rec_count = LOF(nFile) \ rec_size
Leave a comment:
-
Last record in a sequential file
Is there anyway of accessing the last record in a sequential file without reading the whole file?Tags: None
Leave a comment: