I am trying to write a small C program that emulates the unix command
ls -l
. To do so, I am using the stat(2)
syscall and have ran into a small hi
I don't like the if/ else if
syntax.
I prefer use the switch
statement. After struggling a bit I found the way we can do it using different macros, for example:
S_ISCHR (mode)
Is equivalent to:
((mode & S_IFMT) == S_IFCHR)
This allows us to build a switch statement like this:
char f_type(mode_t mode)
{
char c;
switch (mode & S_IFMT)
{
case S_IFBLK:
c = 'b';
break;
case S_IFCHR:
c = 'c';
break;
case S_IFDIR:
c = 'd';
break;
case S_IFIFO:
c = 'p';
break;
case S_IFLNK:
c = 'l';
break;
case S_IFREG:
c = '-';
break;
case S_IFSOCK:
c = 's';
break;
default:
c = '?';
break;
}
return (c);
}
Which in my opinion it's a bit more elegant than the if/else if
approach.