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); }
The fopen() function creates the file if it does not exist. Notes: The fopen() function is not supported for files that are opened with the attributes type=record and ab+, rb+, or wb+ Use the w, w+, wb, w+b, and wb+ parameters with care; data in existing files of the same name will be lost.
C# StreamWriter append text This constructor initializes a new instance of the StreamWriter class for the specified file by using the default encoding and buffer size. If the file exists, it can be either overwritten or appended to. If the file does not exist, the constructor creates a new file.
As long as your program is running, if you keep opening files without closing them, the most likely result is that you will run out of file descriptors/handles available for your process, and attempting to open more files will fail eventually.
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.
FILE *fp = fopen("scores.dat", "ab+");
If you want to read it and then write a new version from scratch, then do it as two steps.
FILE *fp = fopen("scores.dat", "rb"); if (fp) { read_scores(fp); } // Later... // truncates the file FILE *fp = fopen("scores.dat", "wb"); if (!fp) error(); write_scores(fp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With