about summary refs log tree commit diff stats
diff options
context:
space:
mode:
authorKartik K. Agaram <vc@akkartik.com>2021-12-17 08:46:11 -0800
committerKartik K. Agaram <vc@akkartik.com>2021-12-17 08:46:11 -0800
commit12b0a2a7b6f0c87166ae3e9522bb4581cf069957 (patch)
treef328cf9576dc90394394ab7285be1a8ee602778a
parent59ef5da1d9161e249cd1cd8f68b021428f8523c9 (diff)
downloadteliva-12b0a2a7b6f0c87166ae3e9522bb4581cf069957.tar.gz
more protection against data loss
-rw-r--r--src/lua.c4
-rw-r--r--src/tlv.c12
2 files changed, 13 insertions, 3 deletions
diff --git a/src/lua.c b/src/lua.c
index 6e879c0..44b66b4 100644
--- a/src/lua.c
+++ b/src/lua.c
@@ -376,7 +376,7 @@ void save_to_current_definition_and_editor_buffer (lua_State *L, const char *def
   int outfd = mkstemp(outfilename);
   if (outfd == -1) {
     endwin();
-    perror("error in creating temporary file");
+    perror("save_to_current_definition_and_editor_buffer: error in creating temporary file");
     abort();
   }
   FILE *out = fdopen(outfd, "w");
@@ -634,7 +634,7 @@ void save_note_to_editor_buffer (lua_State *L, int cursor) {
   int outfd = mkstemp(outfilename);
   if (outfd == -1) {
     endwin();
-    perror("error in creating temporary file");
+    perror("save_note_to_editor_buffer: error in creating temporary file");
     abort();
   }
   FILE *out = fdopen(outfd, "w");
diff --git a/src/tlv.c b/src/tlv.c
index 33a47e1..32a8d31 100644
--- a/src/tlv.c
+++ b/src/tlv.c
@@ -124,11 +124,20 @@ static void emit_multiline_string(FILE* out, const char* value) {
   }
 }
 
+extern int mkstemp(char *template);
+extern FILE *fdopen(int fd, const char *mode);
 void save_tlv(lua_State* L, char* filename) {
   lua_getglobal(L, "teliva_program");
   int history_array = lua_gettop(L);
   int history_array_size = luaL_getn(L, history_array);
-  FILE *out = fopen(filename, "w");
+  char outfilename[] = "teliva_out_XXXXXX";
+  int outfd = mkstemp(outfilename);
+  if (outfd == -1) {
+    endwin();
+    perror("save_tlv: error in creating temporary file");
+    abort();
+  }
+  FILE *out = fdopen(outfd, "w");
   fprintf(out, "# .tlv file generated by https://github.com/akkartik/teliva\n");
   fprintf(out, "# You may edit it if you are careful; however, you may see cryptic errors if you\n");
   fprintf(out, "# violate Teliva's assumptions.\n");
@@ -172,5 +181,6 @@ void save_tlv(lua_State* L, char* filename) {
     lua_pop(L, 1);
   }
   fclose(out);
+  rename(outfilename, filename);
   lua_pop(L, 1);
 }