Filename Extractor

Last month’s Exercise demonstrated a filename-extractor, but it cheated: The filename was always the same: same text, same length. That’s not always the case in the real world.

The Big Picture view of the Exercise was to pull a filename from a pathname. Pathnames can start anywhere, though a full pathname begins at the root. In Windows, it includes the drive letter, such as C:\. In Unix, full pathnames start in the root directory, /.

You can also have a partial pathname, which might include the ~ home directory shortcut or assume which directory is current. Pathnames can be relative, such as ../../another/directory. And pathnames don’t need to include a filename; a pathname can merely reference a directory. Traditionally, such a pathname terminates with a separator character, / (Unix) or \ (Windows), though this rule isn’t strict.

In my code, I always end a pathname with a separator, / or \. That’s because filenames aren’t prefixed with a separator. Therefore, when I concatenate pathnames, I know that the pathname ends in a separator character and I don’t need to add one before the filename.

For this month’s Exercise, I present a list of six pathnames. Your task is to extract the filename from each pathname. The path may not have a filename, and further the filename may not have an extension.

To assist you, I present the following code skeleton:

#include <stdio.h>

char *filename(char *path)
{   
}   

int main()
{
    char *pathnames[] = {
        "~/Documents/web/images/title.png",
        "/mount/omni/rex/sto/finance",
        "~/Documents/web/media/menu.swf",
        "~/Pictures/family/2011/birthdays/jonah_cake.jpeg",
        "/users/dan/downloads/",
        "yellow.doc"
    };  
    
    /* display all pathnames / filenames */
    for(int x=0;x<6;x++)
    {
    }
        
    return(0);  
}

The bulk of the action occurs in the filename() function, which digests pathnames and spews out the filename portion — if any. The main() function contains the sample pathnames, plus a for loop to process each one.

To further guide you, here is sample output from my solution:

~/Documents/web/images/title.png -> title.png
/mount/omni/rex/sto/finance -> finance
~/Documents/web/media/menu.swf -> menu.swf
~/Pictures/family/2011/birthdays/jonah_cake.jpeg -> jonah_cake.jpeg
/users/dan/downloads/ -> [No filename]
yellow.doc -> yellow.doc

Please attempt to conquer this Exercise on your own. View my solution here.

Leave a Reply