www.digitalmars.com         C & C++   DMDScript  

digitalmars.D.learn - Efficient file search and extract

reply "Sativa" <Sativa mindphuck.com> writes:
Is there a very easy way to search a file for a string, then 
extract to a new file everything from that match on to the end of 
the file?

I basically want to remove a header from a file(it's length is 
not fixed though).

It seems I'm having to convert bytes to chars to strings and back 
and all that mess, which is not very elegant.
Nov 04 2014
parent Jonathan M Davis via Digitalmars-d-learn writes:
On Tuesday, November 04, 2014 20:12:21 Sativa via Digitalmars-d-learn wrote:
 Is there a very easy way to search a file for a string, then
 extract to a new file everything from that match on to the end of
 the file?

 I basically want to remove a header from a file(it's length is
 not fixed though).

 It seems I'm having to convert bytes to chars to strings and back
 and all that mess, which is not very elegant.
By far the easiest would be something like import std.algorithm; import std.file; auto fileContents = std.file.readText("filename"); auto found = fileContents.find(stringImLookingFor); std.file.write("filename", found); though that requires reading the entire file into memory at once. If you're dealing with a text file, that probably isn't a problem though, and any sane alternatives would require writing to a new file and then moving that file to replace the old one, which is more involved. But std.stdio.File and std.stdio.File.byLine can be used to read the file one line at a time, in which case you'd just not write any of the lines until you found a line with the string that you were looking for, in which case you'd write the part of the line that you wanted to a file, and then write every line after that to the file. Or you could use std.mmfile.MmFile to read the whole file as a memory buffer, use find on that to find the portion that you want and then write it to disk (probably with std.file.write), but that definitely requires some casting and probably only makes sense if you want to be able to use find on the whole file at once without necessarily bringing the entire file into memory at once. Personally, I'd just use std.file.readText and std.file.write though. It's simple, and it would only be a problem if you were dealing with a very large file (which text files normally aren't). - Jonathan M Davis
Nov 04 2014