iterate over a directory, dealing with permission errors

John Colvin via Digitalmars-d digitalmars-d at puremagic.com
Fri Sep 18 05:17:23 PDT 2015


On Friday, 18 September 2015 at 11:54:32 UTC, Robert burner 
Schadek wrote:
> On Friday, 18 September 2015 at 11:35:45 UTC, John Colvin wrote:
>> Posting here instead of learn because I think it uncovers a 
>> design flaw
>>
>> void main(string[] args)
>> {
>>     import std.file : dirEntries, SpanMode;
>>     import std.stdio : writeln;
>>     foreach(file; dirEntries(args[1], SpanMode.depth))
>>         writeln(file.name);
>> }
>>
>> Modify this program such that it will print "<file.name> 
>> access denied" instead of crashing with an exception whenever 
>> it hits a permissions problem. Remember that you might not 
>> even have permission to read the directory given in args[1]. 
>> Remember that access permissions can change at any time.
>>
>> It can be done, but it is seriously ugly.
>
> http://dlang.org/phobos/std_exception.html#.handle
>
> foreach(file; dirEntries(args[1], SpanMode.depth)
>         .handle!(Exception, RangePrimitive.front, (e, r) => 
> DirEntry())) {
>     writeln(file.name);
> }
>
> change Exception to the Exception Type to handle and select the 
> throwing range primitive (RangePrimitive). Then just supply a 
> delegate that does the actual handling.
> This will not break any range chain!

That's neat, didn't know about std.exception.handle

Unfortunately, I think there are two problems with your solution:

1) DirIteratorImpl will throw on popFront, not front. I had to 
look at source to find out. Is this a failure of documentation or 
is it actually an implementation detail?

2) it doesn't cover the case where args[1] itself is unreadable, 
because dirEntries will throw when it's created.


More information about the Digitalmars-d mailing list