cstrcmp

C and the strcmp() function


The point of this program is to rename the file extensions of all the files in the current directory.

Here is some of the code:

 while ((dir = readdir(d)) != NULL)
        {
            char *ext = strrchr(dir->d_name, '.');

            if (!strcmp(ext + 1, argv[1])) // :)
            {
                char name[strlen(dir->d_name)];
                strcpy(name, dir->d_name);

                name[strlen(name) - strlen(ext) + 1] = '\0'; // :)
                strcat(name, argv[2]);

                if (rename(dir->d_name, name) != 0)
                {
                    syslog(LOG_ALERT, "Could not rename file %s!", dir->d_name);
                }
            }
        }

I did this for school a long time ago, but I can't understand why the strcmp if-statement works. It looks insane to me.

However, calling it with the arguments "JPG jpg" does indeed rename the JPG-files.

What dark art is at work here?

Thank you in advance.


Solution

  • strcmp() returns an integer value, and an integer is implicitly converted to a Boolean when applied as an operand to a Boolean operator such as !.

    The conversion is zero to false, non-zero to true.

    So !strcmp(ext + 1, argv[1]) is semantically identical to strcmp(ext + 1, argv[1]) == 0.

    Not insane, and a very common idiom amongst those who favour terseness over clarity. You also commonly see it applied to pointers to test for NULL. I would advise against it in general.