-
Notifications
You must be signed in to change notification settings - Fork 5
/
Copy pathlibc.capy
68 lines (56 loc) · 2.59 KB
/
libc.capy
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
// in the future, you wouldn't call `malloc` directly, you'd use an Allocator abstraction
// allocates size bytes of memory. make sure to free() the pointer after your done.
malloc :: (size: usize) -> mut rawptr extern;
// allocates len * size bytes, all the bits are set to 0
calloc :: (len: usize, size: usize) -> mut rawptr extern;
// frees allocated memory
free :: (ptr: rawptr) extern;
// reallocates already allocated memory
realloc :: (ptr: mut rawptr, size: usize) -> mut rawptr extern;
// copies len bytes from dst to src
memcpy :: (dst: mut rawptr, src: rawptr, len: usize) extern;
// prints a string to the screen, adds a newline at the end
puts :: (text: str) extern;
// prints a char to the screen
putchar :: (ch: char) extern;
// a file descriptor is an integer that represents an open file
File_Desc :: distinct i32;
stdin : File_Desc : 0;
stdout : File_Desc : 1;
stderr : File_Desc : 2;
// opens a file
open :: (pathname: str, flags: i32) -> File_Desc extern;
// moves the read/write pointer of a file descriptor
lseek :: (file: File_Desc, offset: isize, whence: i32) -> isize extern;
// closes a file descriptor fd
close :: (file: File_Desc) -> i32 extern;
// writes up to count bytes from the given buffer to
// the file referred to by the file descriptor fd.
write :: (file: File_Desc, buf: ^u8, count: usize) -> isize extern;
// attempts to read up to count bytes from the file into the buf.
// this returns the number of bytes read.
read :: (file: File_Desc, buf: ^mut u8, count: usize) -> isize extern;
// there are two ways to mess with files in libc:
// `*FILE` pointers and file descriptors.
// `FILE` is a struct in libc but it's platform specific,
// so here it's represented by a usize
File_Pointer :: distinct usize;
// opens a file for either reading "r", writing "w", appending "a".
// open a file to update both reading and writing "r+".
// create an empty file for reading and writing "w+".
// open a file for reading and appending "a+".
fopen :: (pathname: str, mode: str) -> File_Pointer extern;
// closes a file
fclose :: (file: File_Pointer) -> i32 extern;
// writes a char to a file
fputc :: (ch: char, file: File_Pointer) -> i32 extern;
// writes a string to a file and doesn't add a newline at the end
fputs :: (text: str, file: File_Pointer) -> i32 extern;
// read a char from a file
fgetc :: (fp: File_Pointer) -> char extern;
// read len char's from a file and store them in buf
fgets :: (buf: ^mut char, len: i32, fp: File_Pointer) -> str extern;
// tests the end-of-file indicator for the given file
feof :: (fp: usize) -> bool extern;
// exits the current program
exit :: (status: i32) extern;