开发者

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

开发者 https://www.devze.com 2023-02-01 14:48 出处:网络
Here\'s how I open a file for writing+ : if( fopen_s( &f, fileName, \"w+\" ) !=0 ) { printf(\"Open file failed\\n\");

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. Wha开发者_运维知识库t'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.


To overwrite any existing file, use the creat call:

#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


Did you try just doing fopen(name, "w")? Also, you should perhaps extend your code to report what error is being signalled, using e.g. perror().

Note

Incidentally, I would avoid (at least most of) MSVC's _s functions despite the warnings. There's very little point in the first place except when:

  1. The original function either writes to a passed-in buffer, but does not have a parameter to specify the size of the buffer (e.g. strcat()), or

  2. The original function was permitted/required to return a pointer to a static buffer (e.g. strerror()), which makes

and these functions are non-portable. In short, most of these functions (including fopon_s()) are gratuitously non-portable -- using them makes your program less portable but gives no benefit. (The incompatible addendum for C can only make things worse -- unless MS implements it, in which case it might only make things more confusing.)

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号