0

I have question about checking if file exists or not. Which option is better?

source=fopen("text.txt","r");
if(source != NULL)
{
    printf("File Exists!\n");
    exit(0);
}

or to use

if (source)
{
    printf("File Exists!\n");
    exit(0);
}
MeChris
  • 717
  • 1
  • 7
  • 11
  • Neither of them is good because some file may not be opened even if it exists. For example, what if you don't have a permission to open it? – MikeCAT Dec 09 '15 at 15:44
  • 2
    Also, you should close opened files. – MikeCAT Dec 09 '15 at 15:44
  • My way, regardless of the programming language, is to assume success and handle failure when necessary. Why to check and only then open? Try to open and know how to handle failures. – Maroun Dec 09 '15 at 15:45
  • @MikeCAT Okay, is there any way to check if the file is there without opening it? I forgot to add that line! Thanks! :) – MeChris Dec 09 '15 at 15:45
  • For POSIX, you can use the `stat` function. – Ian Abbott Dec 09 '15 at 16:10

0 Answers0