Note that there are some explanatory texts on larger screens.

plurals
  1. POWhen is it okay to check if a file exists?
    primarykey
    data
    text
    <p>File systems are volatile. This means that you can't trust the result of one operation to still be valid for the next one, even if it's the next line of code. You can't just say <code>if (some file exists and I have permissions for it) open the file</code>, and you can't say <code>if (some file does not exist) create the file</code>. There is always the possibility that the result of your <code>if</code> condition will <em>change</em> in between the two parts of your code. The operations are distinct: not atomic.</p> <p>To make matters worse, the nature of the problem means that if you're tempted to make this check, odds are you're already worried or aware that something you don't control is likely to happen to the file. The nature of development environments make this event less likely to happen during your testing and very difficult to reproduce. So not only do you have a bug, but the bug won't show up while testing. </p> <p>Therefore under normal circumstances the best course of action is to not even try to check if a file or directory exists. Instead, put your development time into handling exceptions from the file system. You have to handle these exceptions anyway, so this is a much better use of your resources. Even though exceptions are slow, checking the existence of a file requires an extra trip to disk, and disk access is <em>much</em> slower. I even have a well-voted <a href="https://stackoverflow.com/questions/265953/c-how-can-you-easily-check-if-access-is-denied-for-a-file/265958#265958">answer</a> to this effect in another question. </p> <p>But I'm having some doubts. In .Net, for example, if that's really <em>always</em> true, the <code>.Exists()</code> methods wouldn't be in the API in the first place. Also consider scenarios where you <em>expect</em> your program to need to the create file. The first example that comes to mind is for a desktop application. This application installs a default user-config file to it's home directory, and the first time each user starts the application it copies this file to that user's application data folder. It expects the file not to exist on that first startup. </p> <p>So when is it acceptable to check in advance for the existence (or other attributes, like size and permissions) of a file? Is expecting failure rather than success on the first attempt a good enough rule of thumb?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload