C strrchr for POSIX path components
Extract the last component of a path and the name of its parent.
A simple example
strrchr for POSIX path components
- Start with Path notes/a.txt
- Do this Read its final component
- Result a.txt
Syntax
strrchr(path, '/')
Run these examples in C
Save one example at a time as lesson.c. Use C17 on macOS or Linux with a POSIX shell.
cc -std=c17 -Wall -Wextra lesson.c -lm -o lesson
./lessonPrint a receipt name and its folder
A school store receives a path from the checkout system. The receipt printer needs just the filename, while the filing clerk needs the name of the folder that holds it.
#define _POSIX_C_SOURCE 200809L
#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <string.h>
int main(void) {
char receipt[] = "receipts/014.txt";
char *slash = strrchr(receipt, '/');
if (!slash) return 1;
puts(slash + 1);
*slash = '\0';
puts(receipt);
return 0;
}
014.txt receipts
The final component is the receipt name. Its parent supplies the filing category.
Locate a rehearsal score
The choir stores each score inside a season folder. Build the nested path and read its final name for the screen.
Locate a workshop handout
An instructor stores the current template in a class folder. Build the nested path and read its final name for the screen.
What to watch for
These C examples use POSIX file APIs on macOS or Linux. These are pathname operations. A trailing separator or filesystem root may need separate handling.