From 993f24596a4150622b87147911573d7b23fb576a Mon Sep 17 00:00:00 2001 From: emekoi Date: Wed, 16 Oct 2019 12:50:32 -0500 Subject: [PATCH] create file if it doesn't exist when opened --- tte.c | 10 +++++++++- 1 file changed, 9 insertions(+), 1 deletion(-) diff --git a/tte.c b/tte.c index 18c81ec..785d698 100644 --- a/tte.c +++ b/tte.c @@ -1072,13 +1072,21 @@ char* editorRowsToString(int* buf_len) { return buf; } +static int fileExists(const char* file_name) { + struct stat s = {0}; + return stat(file_name, &s) == 0; +} + void editorOpen(char* file_name) { free(ec.file_name); ec.file_name = strdup(file_name); editorSelectSyntaxHighlight(); - FILE* file = fopen(file_name, "r+"); + // If the file dosen't exist, create it, otherwise just open it + const char *mode = fileExists(file_name) ? "r+" : "w+"; + + FILE* file = fopen(file_name, mode); if (!file) die("Failed to open the file");