Last active
July 26, 2025 11:13
-
-
Save vadimkantorov/8a825f67bfe64e7e12478db0e9a70fb5 to your computer and use it in GitHub Desktop.
Demo of strrchr C function
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://en.cppreference.com/w/c/string/byte/strrchr | |
| #include <stdio.h> | |
| #include <string.h> | |
| int main(int argc, char* argv[]) | |
| { | |
| if(argc < 2) | |
| return -1; | |
| const char pathsep = '/'; | |
| const char* path = argv[1]; | |
| const char* slash = strrchr(path, pathsep); | |
| const char* basename = slash ? (slash + 1) : path; | |
| puts(basename); | |
| return 0; | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| // https://en.cppreference.com/w/c/string/byte/strrchr | |
| #include <stdio.h> | |
| #include <string.h> | |
| int main(int argc, char* argv[]) | |
| { | |
| if(argc < 2) | |
| return -1; | |
| const char pathsep = '/'; | |
| char* path = argv[1]; | |
| size_t path_len = strlen(path); | |
| if(path_len > 0 && path[path_len - 1] == pathsep) | |
| path[path_len - 1] = '\0'; | |
| const char* slash = strrchr(path, pathsep); | |
| size_t dirname_len = slash != NULL ? (slash - path) : 0; | |
| if(slash != NULL && dirname_len > 0) | |
| { | |
| path[dirname_len] = '\0'; | |
| puts(path); | |
| } | |
| else if(slash != NULL && dirname_len == 0) | |
| { | |
| path[dirname_len + 1] = '\0'; | |
| puts(path); | |
| } | |
| else | |
| { | |
| puts("."); | |
| } | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment