about summary refs log tree commit diff stats
path: root/src/tlv.c
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 /src/tlv.c
parent59ef5da1d9161e249cd1cd8f68b021428f8523c9 (diff)
downloadteliva-12b0a2a7b6f0c87166ae3e9522bb4581cf069957.tar.gz
more protection against data loss
Diffstat (limited to 'src/tlv.c')
-rw-r--r--src/tlv.c12
1 files changed, 11 insertions, 1 deletions
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);
 }