Versions Compared

Key

  • This line was added.
  • This line was removed.
  • Formatting was changed.

...

Code Block
bgColor#ffcccc
if(!fgets(filename, sizeof(filename), stdio)) {
    /* handle error */
}

if(!open(filename, O_WRONLY, 0600)) {
    /* handle error */
}
/* if filename is a fifo or a locked device the program may now hang in the open call */

...

Programmers can use the POSIX stat() function to obtain information about a named file, and the S_ISREG() macro to determine if the file is a regular file.

Code Block
bgColor#ccccff

struct stat pre_s;
struct stat post_s;
int fildes;

if(!fgets(filename, sizeof(filename), stdio)) {
    /* handle error */
}

if((stat(filename, &pre_s) !== 0) || (!S_ISREG(s.st_mode))) {
    /* handle error */
}

/* due to a race condition here, we will verify with fstat later */

if(!(fildes = open(filename, O_WRONLY, 0600))) {
    /* handle (S_ISREG(error */
}

if(!fstat(fildes, &post_s) {
    /* handle error */
}

if(!(pre_s.st_mode == post_s.st_mode &&
     pre_s.st_ino  == post_s.st_ino  &&
     pre_s.st_dev  == post_s.st_dev)) {
    /* handle error */
}

/* operate on file */
  }
}

Compliant Solution (Windows)

...