@@ -163,6 +163,69 @@ read_entire_file_from_file :: proc(f: ^File, allocator: runtime.Allocator) -> (d
163163 }
164164}
165165
166+ read_entire_file_as_cstring :: proc {
167+ read_entire_file_from_path_as_cstring,
168+ read_entire_file_from_file_as_cstring,
169+ }
170+
171+ @(require_results)
172+ read_entire_file_from_path_as_cstring :: proc (name: string , allocator: runtime.Allocator) -> (data: cstring , size: int , err: Error) {
173+ f := open (name) or_return
174+ defer close (f)
175+ return read_entire_file_from_file_as_cstring (f, allocator)
176+ }
177+
178+ @(require_results)
179+ read_entire_file_from_file_as_cstring :: proc (f: ^File, allocator: runtime.Allocator) -> (data: cstring , size: int , err: Error) {
180+
181+ has_size := false
182+ if size64, serr := file_size (f); serr == nil {
183+ if i64 (int (size64)) == size64 {
184+ has_size = true
185+ size = int (size64)
186+ }
187+ }
188+
189+ if has_size && size > 0 {
190+ total: int
191+ // one extra byte for null terminator
192+ buffer := make ([]byte , size + 1 , allocator) or_return
193+ data = cstring (raw_data (buffer))
194+ for total < size {
195+ n: int
196+ n, err = read (f, buffer[total:size])
197+ total += n
198+ if err != nil {
199+ if err == .EOF {
200+ err = nil
201+ }
202+ size = total
203+ break
204+ }
205+ }
206+ return
207+ } else {
208+ buffer: [1024 ]u8
209+ out_buffer := make ([dynamic ]u8 , 0 , 0 , allocator)
210+ data = cstring (raw_data (out_buffer))
211+ for {
212+ n: int
213+ n, err = read (f, buffer[:])
214+ append_elems (&out_buffer, ..buffer[:n]) or_return
215+ size += n
216+ data = cstring (raw_data (out_buffer))
217+ if err != nil {
218+ if err == .EOF || err == .Broken_Pipe {
219+ err = nil
220+ }
221+ append_nothing (&out_buffer) or_return // null terminator
222+ data = cstring (raw_data (out_buffer))
223+ return
224+ }
225+ }
226+ }
227+ }
228+
166229@(require_results)
167230write_entire_file :: proc (name: string , data: []byte , perm: int = 0o644 , truncate := true ) -> Error {
168231 flags := O_WRONLY|O_CREATE
0 commit comments