Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create a file if one doesn't exist - C

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);     }  
like image 317
karoma Avatar asked Mar 23 '12 14:03

karoma


People also ask

How do you create a file in C if it does not exist?

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.

Does StreamWriter create file if not exist?

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.

What happens if you don't Fclose in C?

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.


1 Answers

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); 
like image 101
Dietrich Epp Avatar answered Oct 05 '22 01:10

Dietrich Epp