www.digitalmars.com         C & C++   DMDScript  

digitalmars.D - Foreach rename deletes files?

reply Ki Rill <rill.ki yahoo.com> writes:
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
Aug 25 2021
parent Ki Rill <rill.ki yahoo.com> writes:
On Thursday, 26 August 2021 at 03:46:37 UTC, Ki Rill wrote:
 I have written a simple D script that helps me rename files in 
 a dataset to the following format: prefix_id.extension.

 [...]
I found the error. It is name clashing; overrides files with existing names.
Aug 26 2021