Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to walk a directory in C

I am using glib in my application, and I see there are convenience wrappers in glib for C's remove, unlink and rmdir. But these only work on a single file or directory at a time.

As far as I can see, neither the C standard nor glib include any sort of recursive directory walk functionality. Nor do I see any specific way to delete an entire directory tree at once, as with rm -rf.

For what I'm doing this I'm not worried about any complications like permissions, symlinks back up the tree (infinite recursion), or anything that would rule out a very naive implementation... so I am not averse to writing my own function for it.

However, I'm curious if this functionality is out there somewhere in the standard libraries gtk or glib (or in some other easily reused C library) already and I just haven't stumbled on it. Googling this topic generates a lot of false leads.

Otherwise my plan is to use this type of algorithm:

dir_walk(char* path, void* callback(char*) {
  if(is_dir(path) && has_entries(path)) {
    entries = get_entries(path);
    for(entry in intries) { dir_walk(entry, callback); }
  }
  else { callback(path) }
}

dir_walk("/home/user/trash", remove);

Obviously I would build in some error handling and the like to abort the process as soon as a fatal error is encountered.

like image 670
mlibby Avatar asked Feb 07 '10 17:02

mlibby


People also ask

What does the walk function do in C?

The walk functions are useful for performing actions like writing files and printing plots. For example, say we used purrr to generate a list of plots. We can now use walk() to print them out.

How do I recurse a directory?

Alternatively referred to as recursive, recurse is a term used to describe the procedure capable of being repeated. For example, when listing files in a Windows command prompt, you can use the dir /s command to recursively list all files in the current directory and any subdirectories.


2 Answers

Have you looked at <dirent.h>? AFAIK this belongs to the POSIX specification, which should be part of the standard library of most, if not all C compilers. See e.g. this <dirent.h> reference (Single UNIX specification Version 2 by the Open Group).

P.S., before someone comments on this: No, this does not offer recursive directory traversal. But then I think this is best implemented by the developer; requirements can differ quite a lot, so one-size-fits-all recursive traversal function would have to be very powerful. (E.g.: Are symlinks followed up? Should recursion depth be limited? etc.)

like image 148
stakx - no longer contributing Avatar answered Sep 24 '22 21:09

stakx - no longer contributing


You can use GFileEnumerator if you want to do it with glib.

like image 33
AndiDog Avatar answered Sep 24 '22 21:09

AndiDog