1
0
mirror of https://gitlab.com/80486DX2-66/gists synced 2024-12-26 02:29:50 +05:30

freadln.c: check if test file exists

This commit is contained in:
Intel A80486DX2-66 2024-04-07 19:48:09 +03:00
parent 889f39ac29
commit 9296a74fb9
Signed by: 80486DX2-66
GPG Key ID: 83631EF27054609B

View File

@ -81,7 +81,9 @@ int freadln(FILE* f, char** output, size_t* length_out) {
}
#ifdef TEST
# include <ctype.h>
# include <inttypes.h>
# include <stdbool.h>
# include <stdint.h>
# 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");