Commit cd3a9793550fd35461a63883702ad30604661dd6

Baptiste 2024-08-07T13:40:07

File.read

diff --git a/.ikc3_history b/.ikc3_history
index eca2693..01f1a6e 100644
--- a/.ikc3_history
+++ b/.ikc3_history
@@ -1,4 +1,3 @@
-(Str) op.sym
 [fd: (S32) -1]
 load("https://git.kmx.io/kc3-lang/kc3/
 )
@@ -97,3 +96,4 @@ Str.starts_with?("abc", "b")
 Str.ends_with?("abc", "b")
 Str.ends_with?("abc", "c")
 Str.ends_with?("abc/", "/")
+File.read("env")
diff --git a/lib/kc3/0.1/file.kc3 b/lib/kc3/0.1/file.kc3
index f101ff1..44c747c 100644
--- a/lib/kc3/0.1/file.kc3
+++ b/lib/kc3/0.1/file.kc3
@@ -15,4 +15,6 @@ defmodule File do
 
   def stat = cfn File.Stat "file_stat" (Str, Result)
 
+  def read = cfn Str "file_read" (Str, Result)
+
 end
diff --git a/libkc3/file.c b/libkc3/file.c
index 70dc7f3..927378f 100644
--- a/libkc3/file.c
+++ b/libkc3/file.c
@@ -19,6 +19,7 @@
 #include <sys/stat.h>
 #include <unistd.h>
 #include "buf.h"
+#include "buf_file.h"
 #include "buf_save.h"
 #include "env.h"
 #include "file.h"
@@ -218,6 +219,29 @@ s_str * file_pwd (s_str *dest)
   return dest;
 }
 
+s_str * file_read (const s_str *path, s_str *dest)
+{
+  s_buf buf;
+  FILE *fp;
+  struct file_stat sb;
+  file_stat(path, &sb);
+  if (! sb.st_mode)
+    return NULL;
+  fp = file_open(path->ptr.pchar, "rb");
+  if (! fp)
+    return NULL;
+  buf_init_alloc(&buf, sb.st_size);
+  if (! buf_file_open_r(&buf, fp)) {
+    fclose(fp);
+    return NULL;
+  }
+  buf_refill(&buf, sb.st_size);
+  buf_read_to_str(&buf, dest);
+  buf_file_close(&buf);
+  fclose(fp);
+  return dest;
+}
+
 s_str * file_search (const s_str *suffix, const s_sym *mode,
                      s_str *dest)
 {
diff --git a/libkc3/file.h b/libkc3/file.h
index 7a2e61a..55d6d1b 100644
--- a/libkc3/file.h
+++ b/libkc3/file.h
@@ -29,6 +29,7 @@ bool    file_access (const s_str *path, const s_sym *mode);
 sw      file_copy (const char *from, const char *to);
 s_str * file_dirname (const s_str *path, s_str *dest);
 s_tag * file_mtime (const s_str *path, s_tag *dest);
+s_str * file_read (const s_str *path, s_str *dest);
 s_str * file_search (const s_str *suffix, const s_sym *mode,
                      s_str *dest);
 s_file_stat * file_stat (const s_str *path, s_file_stat *dest);