I want my program to open a file if it exists, or else create the file. I'm trying the following code but I'm getting a debug assertion at freopen.c. Would I be better off using fclose and then fopen immediately afterward?
FILE *fptr;
fptr = fopen("scores.dat", "rb+");
if(fptr == NULL) //if file does not exist, create it
{
freopen("scores.dat", "wb", fptr);
}
You typically have to do this in a single syscall, or else you will get a race condition.
This will open for reading and writing, creating the file if necessary.
If you want to read it and then write a new version from scratch, then do it as two steps.
If
fptr
isNULL
, then you don't have an open file. Therefore, you can'tfreopen
it, you should justfopen
it.note: Since the behavior of your program varies depending on whether the file is opened in read or write modes, you most probably also need to keep a variable indicating which is the case.
A complete example