Author Topic: Reading a directory  (Read 19262 times)


  • Administrator
  • *****
  • Posts: 19
    • View Profile
Reading a directory
« on: September 24, 2008, 05:49:31 PM »
Q. How do I get a list of file names in a given directory.

A. Check out the ScriptBasic wiki for directory open & close and the nextfile command to get to get a list of file names. (optionally based on a pattern)

Directory Read Information

Code: [Select]
OPEN DIRECTORY dir_name PATTERN pattern_value OPTION option_value AS dir_number

file_name = NEXTFILE

x = EOD(dir_number)



  • SbCollectDirectories Collect the directory names as well as file names into the file list.
  • SbCollectDots Collect the virtual . and .. directory names into the list.
  • SbCollectRecursively Collect the files from the directory and from all the directories below.
  • SbCollectFullPath The list will contain the full path to the file names. This means that the file names returned by the function NextFile will contain the directory path specified in the open directory statement and therefore can be used as argument to file handling commands and functions.
  • SbCollectFiles Collect the files. This is the default behavior.
  • SbSortBySize The files will be sorted by file size.
  • SbSortByCreateTime The files will be sorted by creation time.
  • SbSortByAccessTime The files will be sorted by access time.
  • SbSortByModifyTime The files will be sorted by modify time.
  • SbSortByName The files will be sorted by name. The name used for sorting will be the bare file name without any path even if the option bit SbCollectPath is specified.
  • SbSortByPath The files will be sorted by name including the path. The path is the relative to the directory, which is currently opened. This sorting option is different from the value sbSortByName only when the value sbCollectRecursively is also used.
  • SbSortAscending Sort the file names in ascending order. This is the default behavior.
  • SbSortDescending Sort the file names in descending order.
  • SbSortByNone Do not sort. Specify this value if you do not need sorting. In this case directory opening can be much faster especially for large directories.

Note: Use AND if more then one option is needed with the OPEN DIRECTORY directive.

Here is a bit of code I snagged from my MLS utility that removes old photos of properties that have gone off market. My directory structure is made up of 1000 sub-directories numbered from 000 to 999. The last three digits of the MLS # determines which sub-directory the photo(s) resides in. The following code would read all 1000 directories selecting only .jpg files and print the file names.

Code: [Select]

FOR d = 0 TO 999
  DName = FORMAT("%~000~",d)
  OPEN DIRECTORY DName PATTERN "*.jpg" OPTION sbCollectFiles AS #fn



FName = NEXTFILE(fn)
IF FName = undef THEN RETURN
PRINT FName & "\n"