Listing 1: test.c — Functions to extract a filename with accompanying test program

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
     
void getFileName(char *fullpath, char *filename)
    {
    char *ptr;
    int i = 0;
    if (strlen(fullpath) > 1)
        {
        ptr = strchr(fullpath, '\0');
        while (*ptr != '\\')
            ptr--;
        ptr++;
        while (*ptr!= '.' && *ptr !='\0')
            {
            *(filename + i) = *ptr;
            ptr++;
            i++;
            }
        *(filename + i) = '\0';
        }
    }
     
void getFileName1(char *fullpath, char *filename)
    {
    char *ptr;
    ptr = strrchr(fullpath, '\\');
    if (ptr == NULL)
        ptr = fullpath;
    else
        ptr++;
    strcpy(filename, ptr);
    ptr = strrchr(filename, '.');
    if (ptr != NULL)
        *ptr = '\0';
    }
     
int main(void)
    {
    char fullpath[256], fullpath1[256],
            filename[256], filename1[256];
    strcpy(fullpath, "test\\test.txt");
    strcpy(fullpath1, "test1\\test2\\test1.txt"); 
    getFileName(fullpath, filename);
    getFileName1(fullpath1, filename1);
    printf("End of Test filename: %s\n", filename); 
    printf("End of Test filename1: %s\n", filename1); 
    return 0;
    }