Page 1 of 1
Search for a line in BASIC?
Posted: Sat Jan 01, 2011 5:48 pm
by AlanD
Hi,
Is there a way to have QuickBASIC/VisualBASIC search for a line in a file instead of using individual INPUT #(Number), Variable statments for the line sequentially?
I'm not limited to QB4.5, I have QBasic 1.0, QuickBASIC 4.5, QuickBASIC Professional Development System 7 (7.1 I think.) and VisualBASIC 1.0 for MS-DOS
Thanks,
Alan D.
Posted: Sun Jan 02, 2011 3:46 am
by Theunis
You must open the file as BINARY and then use SEEK to jump to a specific place in a file or a record.
If you are using a sequential file where the records are of variable length then there is no way to accurately calculate where a record starts.
If the records are of fixed length then you merely have to multiply the record number with the length of the record and then use SEEK to jump to the beginning of that record. This of course works fine for Random files where the length of the record is known but it is a useless exercise because with a RANDOM file it is easier to manipulate individual records and it is a more structured programming style.
The only other way I know to use SEEK in a sequential file of variable length is to write an index for the sequential file which will record the start position and the length of each record. This index is then read and with SEEK you can jump directly to that record.
Of course you can convert the sequential file to a RANDOM file. As the Random file is of fixed length it will naturally be longer than the sequential file.
Posted: Sun Jan 02, 2011 4:01 am
by burger2227
If you are looking for text, use INSTR(text$, "String you are looking for..."). It will return an integer value designating the first character position when it finds a match.
You can open a text file and get the whole file as one string up to 32,000 characters.
Code: Select all
OPEN file$ FOR APPEND AS #1 'check that file exists before using INPUT
size& = LOF(1)
CLOSE #1
IF size& THEN
OPEN file$ FOR INPUT AS #1
IF size& <= 32700 THEN ' FORUM post problem!
text$ = INPUT$(size&, 1)
DO
position& = INSTR(text$, search$)
IF position& = 0 THEN EXIT DO
PRINT "Found at:"; position
LOOP
ELSEIF size& > 32700 THEN PRINT "file too large!"
END IF
ELSE KILL file$ 'delete file if empty
END IF
CLOSE #1
Of course you could break larger files into pieces too.
Ted
Posted: Tue Jan 04, 2011 6:12 pm
by AlanD
Thank you very much burger2227 and Theunis. very helpful.
