How do I iteratively replace lines in a file?

Jonathan M Davis jmdavisProg at gmx.com
Sat Mar 19 17:38:37 PDT 2011


On Saturday 19 March 2011 16:51:19 Andrej Mitrovic wrote:
> I'm trying to do something like the following:
> 
> File inputfile;
> foreach (string name; dirEntries(r".\subdir\", SpanMode.shallow))
> {
>     if (!(isFile(name) && getExt(name) == "d"))
>     {
>         continue;
>     }
> 
>     inputfile = File(name, "a+");
> 
>     foreach (line; inputfile.byLine)
>     {
>         if (line == "import foo.d")
>         {
>             inputfile.write("import bar.d");  // or ideally `line = "import
> bar.d"` }
>     }
> }
> 
> That obviously won't work. I think I might need to use the `fseek` function
> to keep track of where I am in the file, or something like that. File I/O
> in D is no fun..

I think that most of the D file I/O stuff is built around the idea of reading in 
the whole file and writing out a whole file rather than editing a file - certainly 
the range-based stuff works that way at the moment. You can probably use 
std.stdio.File.seek to seek to the appropriate position and then write there, 
but I believe that all of the range-based stuff currently is really only for 
reading a file.

Personally, I only ever read in whole files and write out whole files without any 
kind of interleaving, but while that generally works great, it doesn't scale 
once you start dealing with large files. It's likely an area that D's file I/O 
could use some improvement. That may or may not need to be part of the stream 
stuff though.

- Jonathan M Davis


More information about the Digitalmars-d-learn mailing list