Skip to content

Instantly share code, notes, and snippets.

@pankkor
Created June 6, 2023 08:31
Show Gist options
  • Save pankkor/9edbf6a255798e0a972ec2201e0f51aa to your computer and use it in GitHub Desktop.
Save pankkor/9edbf6a255798e0a972ec2201e0f51aa to your computer and use it in GitHub Desktop.
C string view + basename()
// string view
struct sv {
const char *begin;
const char *end;
};
const char *s_dot = ".";
// Custom basename returning string view
struct sv basename(const char *path) {
if (*path == 0) {
return (struct sv){s_dot, s_dot + 1};
}
struct sv prev_sv = {path, path + 1};
struct sv sv = {path, path + 1};
do {
if (*path == '\\' || *path == '/') {
prev_sv = sv;
sv.begin = path + 1;
}
sv.end = ++path;
} while (*path != 0);
sv.end = path;
return sv.end - sv.begin > 0 ? sv : prev_sv;
}
@pankkor
Copy link
Author

pankkor commented Jun 6, 2023

Print string view using %.*s formatting:

struct sv filename_sv = basename(filepath);
printf("%.*s\n", (i32)(filename_sv.end - filename_sv.begin), filename_sv.begin);

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment