diff --git a/c-programming/io/freadln.c b/c-programming/io/freadln.c index 1498812..ea8840c 100644 --- a/c-programming/io/freadln.c +++ b/c-programming/io/freadln.c @@ -81,7 +81,9 @@ int freadln(FILE* f, char** output, size_t* length_out) { } #ifdef TEST +# include # include +# include # include # if POSIX @@ -124,6 +126,15 @@ typedef size_t SIZE_T_FORMAT; # define YN(boolean) ((boolean) ? "yes" : "no") +bool file_exists(const char* path); + +bool file_exists(const char* path) { + FILE* f = fopen(path, "rb"); + return !((f == NULL + /* close file if it was successfully opened */ || (fclose(f), false)) + && errno == ENOENT); +} + int main(void) { // stdin test printf("Type something> "); @@ -136,6 +147,21 @@ int main(void) { // file test #define TEST_FILE "freadln_test.txt" + if (file_exists(TEST_FILE)) { + fflush(stdout); + fprintf(stderr, "Error: A file `" TEST_FILE "` exists. Are you sure " + "you want to continue and\noverwrite it? [[y = Enter]/n]: "); + fflush(stderr); + size_t line_length; + if (finreadln(&line, &line_length) == freadln_ERROR) { + perror("freadln"); + return EXIT_FAILURE; + } else if (line_length >= 1) { + if (tolower(line[0]) == 'n') + return EXIT_FAILURE; + } + } + FILE* f = fopen(TEST_FILE, "w"); if (f == NULL) { perror("fopen");