mirror of
https://gitlab.com/80486DX2-66/gists
synced 2024-12-26 11:30:03 +05:30
freadln.c: check if test file exists
This commit is contained in:
parent
889f39ac29
commit
9296a74fb9
@ -81,7 +81,9 @@ int freadln(FILE* f, char** output, size_t* length_out) {
|
|||||||
}
|
}
|
||||||
|
|
||||||
#ifdef TEST
|
#ifdef TEST
|
||||||
|
# include <ctype.h>
|
||||||
# include <inttypes.h>
|
# include <inttypes.h>
|
||||||
|
# include <stdbool.h>
|
||||||
# include <stdint.h>
|
# include <stdint.h>
|
||||||
|
|
||||||
# if POSIX
|
# if POSIX
|
||||||
@ -124,6 +126,15 @@ typedef size_t SIZE_T_FORMAT;
|
|||||||
|
|
||||||
# define YN(boolean) ((boolean) ? "yes" : "no")
|
# 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) {
|
int main(void) {
|
||||||
// stdin test
|
// stdin test
|
||||||
printf("Type something> ");
|
printf("Type something> ");
|
||||||
@ -136,6 +147,21 @@ int main(void) {
|
|||||||
|
|
||||||
// file test
|
// file test
|
||||||
#define TEST_FILE "freadln_test.txt"
|
#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");
|
FILE* f = fopen(TEST_FILE, "w");
|
||||||
if (f == NULL) {
|
if (f == NULL) {
|
||||||
perror("fopen");
|
perror("fopen");
|
||||||
|
Loading…
Reference in New Issue
Block a user