DS-Homebrew/libslim

Attempt to open inexistent file resut in file being created

Opened this issue · 1 comments

If file f is not present in the filesystem, attempting to

f = fopen("/path", "rb");
if (f) {
  //exists
} else {
  // do not exists.
}

Which makes the library not work when detecting if a file exists with a simple fopen.

The following code seems to be a reliable way of circunventing this issue:

FILE *slim_fopen(const char *path, const char *mode)
{
  bool read = false;

  const char *pmode = mode;

  while (*pmode != '\0') {
    switch (*pmode) {
      case 'r':
        read = true;
        break;

      default:
        break;
    }

    pmode++;
  }

  /* If read is enabled then we need to check if the file exists.  */
  if (read && access(path, F_OK) != 0) {
    /* File do not exist.  */
    return NULL;
  }

  return fopen(path, mode);
}

Call slim_fopen instead of fopen.