Programming Tips - C/C++: How to get the extension of a filename

Date: 2013dec19 Update: 2026sep25 Language: C/C++ Keywords: suffix Q. C/C++: How to get the extension of a filename A.
const char *GetExtensionSimple(const char *filename) { const char *p; if (filename == NULL) return NULL; if ((p = strrchr(filename, '.')) == NULL) return &filename[strlen(filename)]; return p + 1; // Don't include the period }
This handles a NULL filename, or a filename with no extension. There are also library routines for this - but this works everywhere. Full Example:
#include <stdlib.h> #include <stdio.h> #include <string.h> // (Place the above function here) int main() { { const char *filename = "how are you today.mp4"; const char *ext = GetExtensionSimple(filename); printf("ext=%s filename=%s\n", ext, filename); } { const char *filename = "/etc/hosts"; const char *ext = GetExtensionSimple(filename); printf("ext=%s filename=%s\n", ext, filename); } { const char *filename = "/etc/systemd/system.conf"; const char *ext = GetExtensionSimple(filename); printf("ext=%s filename=%s\n", ext, filename); } }
Output:
ext=mp4 filename=how are you today.mp4 ext= filename=/etc/hosts ext=conf filename=/etc/systemd/system.conf