Reputation: 3
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.
Upvotes: 0
Views: 111
Reputation: 93556
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.
Upvotes: 4
Reputation: 31
Let's disassemble it.
if(!strcmp(ext + 1, argv[1]))
ext + 1 is a pointer pointing to the first char of the extension, and argv[1] is pointing to the start of your command line input.
strcmp will compare the two strings, and if it finds that they are the same, it will return 0.
if x equals to 0, then the logical not !x == 1
; otherwise !x == 0
.
in the if-statement, we will run into the embrace IF the condition is NOT 0.
So this statement will do the rename when the extension of the file matches your command line input.
Which part of this statement confused you?
Upvotes: 3