Foreach rename deletes files?

Ki Rill rill.ki at yahoo.com
Thu Aug 26 03:46:37 UTC 2021


I have written a simple D script that helps me rename files in a 
dataset to the following format: prefix_id.extension.

I am using foreach loop and std.file.rename for this purpose. 
After a few tests I have discovered that it deletes files. For 
example, 186 => 177 => 91 => etc...

I traced the problem down to foreach loop, but I still can't 
figure out what is wrong. Is it a side effect of foreach loop?

How can I fix this?

Here is the code:
```D
foreach(i, file; list[0..n]) {
     // retrieve extension, oldName, newName
     immutable extension = (file.canFind(".") ? ("." ~ 
file.split(".")[$-1]) : "");
     immutable oldName = dir.buildPath(file);
     immutable newName = dir.buildPath(prefix ~ i.to!string ~ 
extension);

     writeln("extension: ", extension);
     writeln("oldName: ", oldName);
     writeln("newName: ", newName);

     oldName.rename(newName);
}
```

Any help is greatly appreciated.

Thanks in advance.
Ki




More information about the Digitalmars-d mailing list