solstice

Compute collected power and efficiencies of a solar plant
git clone git://git.meso-star.com/solstice.git
Log | Files | Refs | README | LICENSE

commit 2c4db0843749d074ad8a1d681a2e9ae00ae56a64
parent fa02cd51b86c1c6e1e70c962d680562b163ba416
Author: Vincent Forest <vincent.forest@meso-star.com>
Date:   Wed,  8 Feb 2017 12:05:58 +0100

Protect the write of an existing output file

If the output file exists, ask to the user if he wants to overwrite it.
This commit breaks the build on Windows.

Diffstat:
Msrc/solstice.c | 67++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++-
1 file changed, 66 insertions(+), 1 deletion(-)

diff --git a/src/solstice.c b/src/solstice.c @@ -13,11 +13,28 @@ * You should have received a copy of the GNU General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ +#define _POSIX_C_SOURCE 200112L /* fdopen support */ + #include "solstice.h" #include "solstice_c.h" #include "solstice_args.h" #include "parser/solparser.h" +#include <sys/stat.h> +#include <sys/types.h> + +#include <stdio.h> + +#ifdef OS_WINDOS + /* TODO */ +#else + /* open/close functions */ + #include <errno.h> + #include <fcntl.h> + #include <unistd.h> +#endif + + #include <solstice/ssol.h> /******************************************************************************* @@ -341,6 +358,54 @@ error: goto exit; } +static int +prompt_yes_no(void) +{ + int val[2]; + + do { + fprintf(stderr, "(y/n) "); + + val[0] = getc(stdin); + if(val[0] != '\n' && val[0] != '\r') { + val[1] = getc(stdin); + } + if(val[1] != '\n' && val[1] != '\r') { + while(getc(stdin) != '\n'); /* Flush stdin */ + } + } while((val[1] != '\n' && val[1] != '\r') || (val[0] != 'y' && val[0] != 'n')); + + return val[0] == 'y'; +} + +static FILE* +open_output_stream(const char* name) +{ + int fd = -1; + FILE* fp = NULL; + ASSERT(name); + + fd = open(name, O_CREAT|O_WRONLY|O_EXCL|O_TRUNC, S_IRUSR|S_IWUSR); + + if(fd >= 0) { + fp = fdopen(fd, "w"); + if(fp == NULL) goto error; + } else if(errno == EEXIST) { + fprintf(stderr, "The output file `%s' already exist. Overwrite it? ", name); + if(!prompt_yes_no()) return NULL; + + fd = open(name, O_CREAT|O_WRONLY|O_TRUNC, S_IRUSR|S_IRUSR); + if(fd >= 0 && !(fp = fdopen(fd, "w"))) goto error; + } + +exit: + return fp; +error: + if(fd >= 0) CHECK(close(fd), 0); + fp = NULL; + goto exit; +} + /******************************************************************************* * Solstice local functions ******************************************************************************/ @@ -401,7 +466,7 @@ solstice_init if(!args->output_filename) { solstice->output = stdout; } else { - solstice->output = fopen(args->output_filename, "w+"); + solstice->output = open_output_stream(args->output_filename); if(!solstice->output) { fprintf(stderr, "Could not open the output file `%s'.\n", args->output_filename);