As I mentioned in about this blog post, one of the topics in this blog will be computer trivia.

Let's start.

If you're using Unix, then you'll have noticed that if you type the ls command, it won't show files such as .bashrc or .profile. These files start with a dot and are called hidden files.

If you type ls -a, then you'll see all files, including hidden files.

Why is it that hidden files start with a dot?

The answer is very simple – because it's extremely easy to test if a file is hidden or not by simply testing the first character of the filename, which doesn't involve reading any extra file meta info. As Unix is built using worse-is-better approach then this is a brilliant 90% solution that just works.

Here's how that looks like in C.

I copied the following code from one of my projects. The list_hidden_files function takes a path, loops over all files in this path and finds the hidden files with a simple if check:

int list_hidden_files (const char *path)
{
    DIR *dir;
    struct dirent *de;

    dir = opendir(path);
    if (dir == NULL)
        return -1;

    while ((de = readdir(dir))) {
        if ((de->d_name)[0] == '.') {
            printf("hidden file: %s\n", de->d_name);
        }
    }

    closedir(dir);
    return 0;
}

As you can see in the while loop, testing for a hidden file is as easy as testing if the first character of the filename starts with a ..

See you next time!