SDDSlib
Loading...
Searching...
No Matches
fopen_e.c File Reference

Provides the fopen_e function for opening files with error checking and handling. More...

#include "mdb.h"

Go to the source code of this file.

Functions

FILE * fopen_e (char *file, char *open_mode, long mode)
 Opens a file with error checking, messages, and aborts.
 

Detailed Description

Provides the fopen_e function for opening files with error checking and handling.

License
This file is distributed under the terms of the Software License Agreement found in the file LICENSE included with this distribution.
Author
C. Saunders, R. Soliday

Definition in file fopen_e.c.

Function Documentation

◆ fopen_e()

FILE * fopen_e ( char * file,
char * open_mode,
long mode )

Opens a file with error checking, messages, and aborts.

This function attempts to open a file with the specified mode. If the file exists and the mode includes FOPEN_SAVE_IF_EXISTS, it renames the existing file by appending a tilde (~). If opening the file fails, it either returns NULL or exits the program based on the mode flags.

Parameters
fileThe path to the file to open.
open_modeThe mode string for fopen (e.g., "r", "w").
modeFlags controlling behavior (e.g., FOPEN_SAVE_IF_EXISTS, FOPEN_RETURN_ON_ERROR).
Returns
FILE* Pointer to the opened file, or NULL if FOPEN_RETURN_ON_ERROR is set and the file could not be opened.

Definition at line 30 of file fopen_e.c.

30 {
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