Skip to content

Commit 816696e

Browse files
committed
Add read_entire_file_as_cstring to os2
1 parent 935d965 commit 816696e

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

core/os/os2/file_util.odin

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -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)
167230
write_entire_file :: proc(name: string, data: []byte, perm: int = 0o644, truncate := true) -> Error {
168231
flags := O_WRONLY|O_CREATE

0 commit comments

Comments
 (0)