dos – Alternative to dir command to query a directory in C

Exception or error:

I am trying to create a program where the user can add different path regex-s so that a specific set of operations on the files that match the regex.

I tried using opendir() of the dirent.h header file but soon realized that it does not use the concept of regex.

The dir command I am trying to emulate is

dir [regex] /b

I need the output in a (char) buffer**. Piping the output could be a solution but I am looking for a more efficient way to do it.

Is there any predefined function in the standard (C90) library or will we have to create our own implementation?

How to solve:

C does not know about directories. They are operating system specific, usually provided by your OS kernel (look however inside GNU Hurd as an exception, and into unikernels). Read the C11 standard n1570 and forget, in 2020, about the obsolete C89 standard and TurboC. Consider trying some Linux distribution (such as Ubuntu or Debian or others). Most of them provide GCC or Clang (or the non-optimizing TinyCC compiler) and are very developer-friendly. My recommendation: use GCC as gcc -Wall -Wextra -g. Choose a good enough built automation tool (maybe GNU make) with an appropriate source-code editor (such as GNU emacs or vim or geany or others). Learn how to debug small programs and use the GDB debugger and the git version control tool.

POSIX does know about directories (it is an API specification written in English, also defining regex(3)). See here, and read the Linux man pages. And also the WinAPI.

On Linux, see mkdir(2), chdir(2), readdir(3), getcwd(3), unlink(2), stat(2), open(2), nftw(3), path_resolution(7) etc etc; you could want to study the source code of a Linux kernel and of some common C library for it, such as GNU glibc or musl-libc. Budget for that several months full time of your efforts. They are open source, so with some conditions you are allowed to study, improve and reuse their source code. See also

Notice also popen. You probably don’t want to use it and would prefer using more primitive system calls (see syscalls(2) for their list on Linux). You could use a library like Glib (from GTK).

Remember that C programs (of the freestanding kind) could run on the bare metal (e.g. Arduino). In those cases, speaking of directories does not make any sense. See also for more, and observe that the Linux kernel is written in C (with a tiny amount of assembler code).

GrassHopper was an OS written mostly in C without any files or directories. See also old discussions archived on and tccboot.


You can use system() function as an alternative. The info about how to use system() function is easily available.

Leave a Reply

Your email address will not be published. Required fields are marked *