How do I open a file in such a way that if the file doesn't exist it will be created and opened automatically?

Posted by snakile on Stack Overflow See other posts from Stack Overflow or by snakile
Published on 2010-12-27T16:53:26Z Indexed on 2010/12/27 20:53 UTC
Read the original article Hit count: 166

Filed under:
|
|

Here's how I open a file for writing+ :

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

If the file doesn't exist the open operation fails. What's the right way to fopen if I want to create the file automatically if the file doesn't already exist?

EDIT: If the file does exist, I would like fprintf to overwrite the file, not to append to it.

© Stack Overflow or respective owner

Related posts about c

    Related posts about file-io