DS-Homebrew / libslim

libelm revival using FatFs 0.14 with libfat compatible API
BSD 3-Clause "New" or "Revised" License
11 stars 4 forks source link

Attempt to open inexistent file resut in file being created #9

Open giulianobelinassi opened 1 year ago

giulianobelinassi commented 1 year ago

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.

giulianobelinassi commented 1 year ago

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.