How do I iteratively replace lines in a file?

Ali Çehreli acehreli at yahoo.com
Sun Mar 20 00:05:38 PDT 2011


On 03/19/2011 04:51 PM, 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.

That's not a good idea with text files.

Even for binary files, the file must have a well defined format. It is 
not possible to insert or remove bytes from a file due to low level 
reasons. The file systems that I am aware of don't provide such interfaces.

And writing after fseek would overwrite existing data.

Like Jonathan M Davis said, the best is to read from the source and 
write to the destination.

Ali



More information about the Digitalmars-d-learn mailing list