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 a while back, 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.
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 totrue.So
!strcmp(ext + 1, argv[1])is semantically identical tostrcmp(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.