Versions Compared

Key

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

...

In the following noncompliant code, unsafe characters are used as part of a file name.

Code Block
bgColor#ffcccc
langc
#include <fcntl.h>
#include <sys/stat.h>

int main(void) {
   char *file_name = "&#xBB;&#xA3;???&#xAB;";
   mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

   int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode);
   if (fd == -1) {
      /* Handle Error */
   }
}

...

Use a descriptive file name, containing only the subset of ASCII previously described.

Code Block
bgColor#ccccff
langc
#include <fcntl.h>
#include <sys/stat.h>

int main(void) {
   char *file_name = "name.ext";
   mode_t mode = S_IRUSR | S_IWUSR | S_IRGRP | S_IROTH;

   int fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, mode);
   if (fd == -1) {
      /* Handle Error */
   }
}

...

This noncompliant code example is derived from rule FIO30-C. Exclude user input from format strings, except that a newline is removed on the assumption that fgets() will include it.

Code Block
bgColor#FFCCCC
langc
char myFilename[1000];
const char elimNewLn[] = "\n";

fgets(myFilename, sizeof(myFilename)-1, stdin);
myFilename[sizeof(myFilename)-1] = '\0';
myFilename[strcspn(myFilename, elimNewLn)] = '\0';

...

In this compliant solution, the program rejects file names that violate the guidelines for selecting safe characters.

Code Block
bgColor#ccccFF
langc
char myFilename[1000];
const char elimNewln[] = "\n";
const char badChars[] = "-\n\r ,;'\\<\"";
do {
  fgets(myFilename, sizeof(myFilename)-1, stdin);
  myFilename[sizeof(myFilename)-1] ='\0';
  myFilename[strcspn(myFilename, elimNewln)]='\0';
} while ( (strcspn(myFilename, badChars))
           < (strlen(myFilename)));

...