Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dir() function understanding

' Display the names in C:\ that represent directories.
MyPath = "c:\"   ' Set the path.
MyName = Dir(MyPath, vbDirectory)   ' Retrieve the first entry.
Do While MyName <> ""   ' Start the loop.
      ' Use bitwise comparison to make sure MyName is a directory. 
      If (GetAttr(MyPath & MyName) And vbDirectory) = vbDirectory Then 
         ' Display entry only if it's a directory.
         MsgBox(MyName)
      End If   
   MyName = Dir()   ' Get next entry.
Loop

I am looking at the above code. I specifically don't understand what the "MyName = Dir()" does. It is commented it gets the next entry, but I don't understand how it gets the next entry - specifically what is Dir() doing?

like image 352
james1395 Avatar asked Sep 01 '16 14:09

james1395


2 Answers

Dir is function which has a edge effect.

the first call to Dir: MyName = Dir(MyPath, vbDirectory) initializes the Dir internals and returns the first directory entry.

Subsequent calls to Dir use the same context, yielding MyPath directory contents one by one.

It's not reentrant (which is also why you can't nest/recurse multiple loops using Dir), not very elegant, but that's how it works.

like image 110
Jean-François Fabre Avatar answered Nov 09 '22 14:11

Jean-François Fabre


According to the Dir() MSDN, it

Returns a string representing the name of a file, directory, or folder that matches a specified pattern or file attribute, or the volume label of a drive.

like image 45
Chrismas007 Avatar answered Nov 09 '22 13:11

Chrismas007