SDDSlib
Loading...
Searching...
No Matches
fopen_e.c
Go to the documentation of this file.
1/**
2 * @file fopen_e.c
3 * @brief Provides the fopen_e function for opening files with error checking and handling.
4 *
5 * @copyright
6 * - (c) 2002 The University of Chicago, as Operator of Argonne National Laboratory.
7 * - (c) 2002 The Regents of the University of California, as Operator of Los Alamos National Laboratory.
8 *
9 * @license
10 * This file is distributed under the terms of the Software License Agreement
11 * found in the file LICENSE included with this distribution.
12 *
13 * @author C. Saunders, R. Soliday
14 */
15
16#include "mdb.h"
17
18/**
19 * @brief Opens a file with error checking, messages, and aborts.
20 *
21 * This function attempts to open a file with the specified mode. If the file exists and the mode includes
22 * `FOPEN_SAVE_IF_EXISTS`, it renames the existing file by appending a tilde (`~`). If opening the file fails,
23 * it either returns `NULL` or exits the program based on the mode flags.
24 *
25 * @param file The path to the file to open.
26 * @param open_mode The mode string for `fopen` (e.g., "r", "w").
27 * @param mode Flags controlling behavior (e.g., `FOPEN_SAVE_IF_EXISTS`, `FOPEN_RETURN_ON_ERROR`).
28 * @return FILE* Pointer to the opened file, or `NULL` if `FOPEN_RETURN_ON_ERROR` is set and the file could not be opened.
29 */
30FILE *fopen_e(char *file, char *open_mode, long mode) {
31 FILE *fp;
32 static char buffer[1024];
33
34 if ((mode & FOPEN_SAVE_IF_EXISTS) && fexists(file)) {
35 sprintf(buffer, "%s~", file);
36 if (rename(file, buffer) != 0) {
37 fprintf(stderr, "error: cannot save previous version of %s--new file not opened.\n", file);
38 if (mode & FOPEN_RETURN_ON_ERROR)
39 return (NULL);
40 exit(1);
41 }
42 }
43
44 if ((fp = fopen(file, open_mode))) {
45 if (mode & FOPEN_INFORM_OF_OPEN)
46 printf("%s opened in mode %s\n", file, open_mode);
47 return (fp);
48 }
49
50 sprintf(buffer, "unable to open %s in mode %s", file, open_mode);
51 perror(buffer);
52
53 if (!(mode & FOPEN_RETURN_ON_ERROR))
54 exit(1);
55
56 return (NULL);
57}
long fexists(const char *filename)
Checks if a file exists.
Definition fexists.c:27
FILE * fopen_e(char *file, char *open_mode, long mode)
Opens a file with error checking, messages, and aborts.
Definition fopen_e.c:30