On Wednesday 20 January 2010 10:24:44 am Daniel Dilts wrote:
> Does anybody have any suggestions of how to improve this so that it
>  handles all of the possible error conditions and be more readable?

Writing code is always an art form comparable to poetry.  So I have 
rewritten your code (I won't make any guarantees that it will work) to my 
style.

What I did was take out the do statement and the breaks and used if/else 
statements.  So, if you try to open the directory and it fails, the code 
will jump to the else statement and display the error and set the return 
value.  The same (hopefull) with the other statements.  So we nest and nest 
if statements (which can get ugly) but we separate the running code from the 
error handling.

What you did would make more sense in C++ where instead of setting an error 
code and breaking out of the do statement you would simply throw an 
exception.

Warning: this may not compile, this may not even work!  But, at least it 
provides a different version of your code.  Enjoy!

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;

  // Try to open the directory
  if ((dir = opendir(dirName) != NULL) {
    // Read the directory contents
    while ((entry = readdir(dir) != NULL) {
        size_t temp = strlen(entry->d_name);
        if (temp > width) {
          width = temp;
        }
        ++height;
    }
    else {
      perror("Error iterating directory");
      error = errno;
      errno = 0;
    }

    rewinddir(dir);
  
    if ((pad = newpad()) != NULL) {
      while (NULL != (entry = readdir(dir))) {
        if (errno != 0) {
          perror("Error iterating directory");
          error = errno;
          errno = 0;
        }
      }
    }
    else {
      perror("Error creating directory pad");
      error = errno;
      errno = 0;
    }
    }
  }
  else {
    // Couldn't open the directory
    perror("Failed to open directory");
    error = errno;
    errno = 0;
  }

  return error;
};

-- 
Alberto Treviño
BYU Testing Center
Brigham Young University
--------------------
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

Reply via email to