Re: Open File For Input Method Faster Than File System Object Stream?
- From: "Mike Williams" <mikea@xxxxxxxxxxxxxxxxx>
- Date: Fri, 30 May 2008 11:06:39 +0100
<cc77lemon@xxxxxxxxx> wrote in message news:3c0e5fb0-d547-4689-97a3-5ebbcf784fc9@xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
I have about 200 text files where I am trying to read
data from certain lines depending if certain text values
can be found using instr . . . but there are some text
files that are missing Carriage Returns and only have
Line Feeds, and in those files the 'Open File For Input'
method farts. Meaning, it doesn't move line by line.
There are all sorts of different ways of tackling this problem. Much depends on exactly what you are doing, and the best method to advise would depend chiefly on whether you are interested in only the first occurrence of the substring in the file or whether you want to check every line of the file for that substring. Assuming the latter, one very simple method would be to load the entire text file into a single String, as in:
Dim s1 As String, fn As Long
fn = FreeFile
Open "c:\temp\myfile.txt" For Binary As fn
s1 = Space$(LOF(fn))
Get #fn, 1, s1
Close fn
You could then use Instr in a loop to run through the entire string (s1) just once, searching for and recording (in an array of Longs) the position of every linefeed character it finds. Then loop again with Instr, this time searching for your desired substring. Each time you find an occurrence of the substring you simply check the array of Longs in reverse order looking for the first element that contains a value less than the position at which Instr found the substring, which will tell you which "line" of the original file the substring is in. You can then extract that line of text from the main string (s1) if you wish to do so.
Alternatively, once you have loaded the entire text file into the main string (s1 above) you could use the VB Split function on the character 10 (line feed) to split the string into an array of substrings. Each element of the returned String array will then contain one "line" of the original file (with or without a Chr(13) depending on the file) and you can then run through that array of Strings one by one in much the same way as you are doing now.
There are all sorts of different ways, and I'm sure others here will come up with a number of other alternatives, but the above methods will be reasonably fast and in fact the first method will be very fast indeed.
Mike
.
- References:
- Prev by Date: Re: Open File For Input Method Faster Than File System Object Stream?
- Next by Date: Re: An empty question
- Previous by thread: Re: Open File For Input Method Faster Than File System Object Stream?
- Index(es):
Relevant Pages
|
Loading