I've started playing around with C and I'm wondering if anybody can tell me
how to improve my code. This function just iterates over a directory. It
is a really simple function, but the error handling takes up so much space
that it is difficult to follow the flow of the code.
Does anybody have any suggestions of how to improve this so that it handles
all of the possible error conditions and be more readable? I was thinking I
could at least use some preprocessor macros to hide much of the if(){...}
blocks behind them.
int setupDirectoryPad(WINDOW ** pad, const char * dirName) {
int error = 0;
DIR * dir = NULL;
struct dirent * entry = NULL;
size_t width = 0;
size_t height = 0;
pad = NULL;
do {
errno = 0;
if (NULL == (dir = opendir(dirName))) {
perror("Failed to open directory");
error = errno;
errno = 0;
break;
}
errno = 0;
while (NULL != (entry = readdir(dir))) {
size_t temp = strlen(entry->d_name);
if (temp > width)
width = temp;
++height;
}
if (errno != 0) {
perror("Error iterating directory");
error = errno;
errno = 0;
break;
}
rewinddir(dir);
if (NULL == (pad = newpad())) {
perror("Error creating directory pad");
error = errno;
errno = 0;
break;
}
errno = 0;
while (NULL != (entry = readdir(dir))) {
}
if (errno != 0) {
perror("Error iterating directory");
error = errno;
errno = 0;
break;
}
} while(false);
if (NULL != dir) {
errno = 0;
if (0 != closedir(dir)) {
perror("Failed to close directory");
error = errno;
errno = 0;
}
}
return error;
}
--------------------
BYU Unix Users Group
http://uug.byu.edu/
The opinions expressed in this message are the responsibility of their
author. They are not endorsed by BYU, the BYU CS Department or BYU-UUG.
___________________________________________________________________
List Info (unsubscribe here): http://uug.byu.edu/mailman/listinfo/uug-list