Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

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

Open
giulianobelinassi opened this issue Mar 14, 2023 · 1 comment
Open

Comments

@giulianobelinassi
Copy link

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
Copy link
Author

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant