What happens if you open a file already open?

  • 12
    Have you tried? And what happened? - VladD
  • 2
    You can open in different ways: for reading / writing; - cpp_user

1 answer 1

It depends on which share flags were set when the file was opened for the first time. For example, if only the share-flag of the prohibition on writing was set and the second time opening is performed for reading, then everything is fine, if we open for writing, we get an access violation error, we will not open it.

An example, here we prohibit the reopening of a record:

FILE *FP = _fsopen("filename".txt", "a+", _SH_DENYWR); 

The constants _SH_Xxx are defined in share.h - do not forget to add #include <share.h>

_fsopen, _wfsopen on MSDN

As I understand it, you are particularly interested in error handling. First of all, we check if the result is not 0. If not, then this is a valid file pointer. If 0, then we see what errno equals.