Video Coming Soon...

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

31: basename/dirname

In this exercise I'll give you a little bit of starter code to base your version on. You'll be making the basename and dirname tools which both print out parts of a path.

The Challenge

The challenge this time is simple. Below I have the code for basename. Take this code and make a first version of basename from GNU coreutils that supports the -a option.

Once you have a first version of basename working, use it to create a version of dirname. They're very similar so you should be able to copy your basename code and alter it, but this time I want you to recreate it from what you learned in basename.

That means, start over with a new dirname project, try to create it using only what you know, and only refer to your basename code when you get stuck.

The Code

Here's your starting code for basename:

View Source file basename.cpp Only

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

int main(int argc, char* argv[]) {
  std::string filename{argv[1]};

  std::filesystem::path fp{filename};

  fmt::println("{}", fp.stem().string());
}

See my first version of dirnameView Source file dirname.cpp Only

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

int main(int argc, char* argv[]) {
  std::string filename{argv[1]};

  std::filesystem::path fp{filename};

  fmt::println("{}", fp.parent_path().string());
}

The Discussion

Cross platform paths is a fairly difficult topic, mostly because Microsoft can't figure out what they want. Do they want / or \? Do they support things like ~ or not? The std::filesystem::path fairly decent but always keep in mind that there are different failures that can happen on Windows.

Most of your manipulation of paths will work, but I believe if you deal with Unicode paths or any network drives then Windows gets weird. Always, always, test your path manipulation code on Windows with weird characters in paths like spaces in names, unicode emojis, and foreign language names.

One thing you are always allowed to do is declare what your program supports. If you find it has problems with emoji files on Windows then simply detect the emoji files and abort telling the user you don't support that. As long as they know it's not supported they can either not use your software or stop being weirdos and name their files like a sane person.

Further Study

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.