...
This compliant solution uses the x
mode character to instruct fopen()
to fail rather than open an existing file.:
Code Block | ||||
---|---|---|---|---|
| ||||
char *file_name; /* Initialize file_name */ FILE *fp = fopen(file_name, "wx"); if (!fp) { /* Handle error */ } |
...
For code that operates on FILE
pointers and not file descriptors, the POSIX fdopen()
function can be used to associate an open stream with the file descriptor returned by open()
, as shown in this compliant solution [Open Group 2004].:
Code Block | ||||
---|---|---|---|---|
| ||||
char *file_name; int new_file_mode; FILE *fp; int fd; /* Initialize file_name and new_file_mode */ fd = open(file_name, O_CREAT | O_EXCL | O_WRONLY, new_file_mode); if (fd == -1) { /* Handle error */ } fp = fdopen(fd, "w"); if (fp == NULL) { /* Handle error */ } |
...