How to open a file in such a way that if the file does not exist, it will be created and opened automatically?

This is how I open the file for writing +:

if( fopen_s( &f, fileName, "w+" ) !=0 ) {
    printf("Open file failed\n");
    return;
}
fprintf_s(f, "content");

If the file does not exist, the open operation fails. What is the right way for fopenif I want to create a file automatically if the file does not already exist?

EDIT: If the file exists, I would like fprintf to overwrite the file rather than adding it.

+3
source share
2 answers

To overwrite any existing file, use the call creat:

#include <fcntl.h>
#include <stdio.h>

int fd = creat (fileName, 0666);  // creates file if not exist, overwrite existing
FILE *f = fdopen (fd, "w");  // optional, if FILE * type desired
+2
source

fopen(name, "w")? , , , , , , perror().

, ( , ) MSVC _s, . , , , :

  • , (, strcat())

  • / (, strerror()),

. , ( fopon_s()) - , . ( C - MS , .)

+2

Source: https://habr.com/ru/post/1782318/


All Articles