Video Coming Soon...

Created by Zed A. Shaw Updated 2026-04-30 02:05:52

34: ls

You're now going to create the tool that lists the contents of directories called ls. The ls command is very complicated, with many strange options and hidden features. For example, if you run ls in a terminal it tries to figure out how wide your terminal is so that the results can be tabulated to fit, but if you run ls > files.txt to put the list into a file it will not look at your terminal and only print the list.

That's why when you go to the documentation for ls it's a page referencing many other pages. It's better to read the Linux man page for ls and use that for your guide.

The Challenge

You are to make an ls that supports the following options:

For these tasks you'll also need the following APIs from the standard library:

On the filesystem::status page there's an example you should study, then scroll down and there's functions you'll need.

The Code

Here's my first simplified version of ls that only lists visible files in the current directory:

See my first version of lsView Source file ls.cpp Only

#include <fmt/core.h>
#include <filesystem>

namespace fs = std::filesystem;

int main(int argc, char* argv[]) {
  for(int i = 1; i < argc; i++) {
    fs::path target{argv[i]};

    for(auto& dir_entry : fs::directory_iterator{target}) {
      const std::string& path = dir_entry.path().filename().string();

      if(!path.starts_with(".")) {
        fmt::println("{}", path);
      }
    }
  }
}

The Discussion

You could probably spend a long time making a replica of ls and learn many things about how files are stored on your computer. It covers everything from how to process a directory recursively to what file permissions are. You can also get into the weird terminal stuff that ls uses to format its output. It's a deceptively simple program with many secrets.

The term "recursive" means to "repeat on itself" but in the context of directories it means "do this thing to this directory and all of its child directories."

Further Study

Probably the most involved thing you could do is make recursive directory listing work. To do this you'd need to identify directories, and if -R is given then list the contents of each directory. You'll want to run ls -R to see how ls does this.

You can also try to create the actual ls -l output, which lists all sorts of information about each file. Doing this would probably involve most of the std::filesystem API to collect the information, which would make you more of an expert in std::filesystem than most people.

Previous Lesson Next Lesson

Register for Learn C++ the Hard Way

Register to gain access to additional videos which demonstrate each exercise. Videos are priced to cover the cost of hosting.