2.11.2. Dealing with directories and files

Learning objectives

Functions from file.h

LEDA offers some auxiliary functions that allow to traverse directories comfortably and platform-independently and to get information about the files residing there. These functions are declared in the header file file.h.

The following program uses some of these functions to traverse all subdirectories recursively by means of a function visit_directory(), starting from the current directory; it outputs the names of all files contained therein, together with their size. To depict the tree structure of the directories, the recursive function outputs an appropriate number of blanks before every file name; this number grows with the recursion depth.

Filename: FileBrowser.C
LEDA users as of version 5.0: Note that header files are now partitioned into modules (subfolders)!
#include <LEDA/file.h>
#include <LEDA/list.h>
#include <LEDA/string.h>
#include <iostream>

using leda::get_files;
using leda::size_of_file;
using leda::get_directories;

using leda::list;
using leda::string;
using std::cout;

void visit_directory(const string& new_dir, const string& padding = "") 
{
  set_directory(new_dir);

  string f;
  list<string>  files_in_dir = get_files(".");
  forall(f, files_in_dir) 
    cout << padding << f << " " << size_of_file(f) << "\n";
  

  list<string> dirs_in_dir(get_directories("."));
  string dir;
  forall(dir, dirs_in_dir) 
    if(dir != "."  && dir != "..") {
      cout << padding << dir << "/\n";
      visit_directory(dir, padding + "  ");
    }

  set_directory(string(".."));
}


int main()
{
  visit_directory(".");
}

At first, our function visit_directory() goes and stands by means of

set_directory(dir);

into the directory dir passed to it. Then it lists all files contained therein with the help of

get_files(dir);

It obtains the file size of a certain file f by

size_of_file(f);

After that, by means of a

get_directories(dir);

all directories starting out from the current directory are determined. The parent directory and a reference to the current directory itself are also part of this list. These directories can be accessed platform-independently by .. and by ., respectively; no recursive call must be carried out for them.

Further information

Some further useful functions are declared in the file.h; they ease for example the creation of directories or the deletion of files. One finds more information about these functions on the corresponding manual page.




Imprint-Dataprotection