Remove File Extension from Filename in Zig
Get the filename without its extension using std.fs.path.stem.
This recipe was written using Zig version
0.15.2. If this recipe is outdated, please let me know on X (@sepyke) or Bluesky (@pyk.sh).
When working with file paths in Zig, you often need to extract just the base
name of a file without its extension. For example, if you have
basic_example.zig, you might want to get basic_example to use as an
executable name. Zig’s standard library provides a convenient function for this:
std.fs.path.stem.
The std.fs.path.stem function takes a []const u8 (a slice of bytes
representing the path) and returns a []const u8 which is the last component of
the path without its extension. It handles various cases, including paths with
multiple dots in the extension or no extension at all.
Here’s how you can use it:
const std = @import("std");
const fs = std.fs;
pub fn main() !void {
const filename1 = "basic_example.zig";
const filename2 = "archive.tar.gz";
const filename3 = "document";
const filename4 = ".bashrc"; // Hidden file, stem returns ".bashrc"
std.debug.print("Original: {s}, Stem: {s}\n", .{ filename1, fs.path.stem(filename1) });
std.debug.print("Original: {s}, Stem: {s}\n", .{ filename2, fs.path.stem(filename2) });
std.debug.print("Original: {s}, Stem: {s}\n", .{ filename3, fs.path.stem(filename3) });
std.debug.print("Original: {s}, Stem: {s}\n", .{ filename4, fs.path.stem(filename4) });
}Make sure Zig is installed:
$ zig version
0.15.2Then run it:
$ zig run remove_extension.zig
Original: basic_example.zig, Stem: basic_example
Original: archive.tar.gz, Stem: archive.tar
Original: document, Stem: document
Original: .bashrc, Stem: .bashrc