libpulsar
A modular compiler for the pulsar programming language
Loading...
Searching...
No Matches
src
util
io.c
Go to the documentation of this file.
1
// Copyright (C) 2023 Ethan Uppal. All rights reserved.
2
3
#include <stdlib.h>
// exit, malloc
4
#include <stdio.h>
// FILE et al.
5
#include "
io.h
"
6
7
void
ps_file_ctx_init
(
struct
ps_file_ctx
* file_ctx,
STR
filename,
char
*
buffer
,
8
usize
length
) {
9
file_ctx->
filename
= filename;
10
file_ctx->
buffer
=
buffer
;
11
file_ctx->
length
=
length
;
12
}
13
14
char
*
ps_read_file_safe
(
const
char
* filename,
isize
* length_ext) {
15
FILE* file = fopen(filename,
"r"
);
16
if
(!file) {
17
perror(
"fopen"
);
18
exit(1);
19
}
20
21
if
(fseek(file, 0, SEEK_END) == -1) {
22
perror(
"fseek"
);
23
exit(1);
24
}
25
long
length
= ftell(file);
26
*length_ext =
length
;
27
if
(
length
== -1) {
28
perror(
"ftell"
);
29
exit(1);
30
}
31
rewind(file);
32
33
char
*
buffer
= malloc(
length
+ 1);
34
if
(!
buffer
) {
35
perror(
"malloc"
);
36
exit(1);
37
}
38
39
if
(fread(
buffer
,
sizeof
(
char
),
length
, file) != (
unsigned
long
)
length
) {
40
perror(
"fread"
);
41
exit(1);
42
}
43
buffer
[
length
] = 0;
44
45
if
(fclose(file) == EOF) {
46
perror(
"fclose"
);
47
exit(1);
48
}
49
50
return
buffer
;
51
}
STR
#define STR
Definition
def.h:40
isize
#define isize
Definition
def.h:49
usize
#define usize
Definition
def.h:50
ps_file_ctx_init
void ps_file_ctx_init(struct ps_file_ctx *file_ctx, STR filename, char *buffer, usize length)
Initializes file_ctx to describe the given file (filename, buffer, length).
Definition
io.c:7
ps_read_file_safe
char * ps_read_file_safe(const char *filename, isize *length_ext)
Definition
io.c:14
io.h
Defines safe file I/O functions.
buffer
char buffer[ITOA_BUFFER_SIZE]
Definition
itoa.c:11
length
static void usize length
Definition
lexer.h:71
ps_file_ctx
Information captured in a file necessary for effective info/error reporting.
Definition
io.h:15
ps_file_ctx::length
usize length
Definition
io.h:18
ps_file_ctx::buffer
char * buffer
Definition
io.h:17
ps_file_ctx::filename
STR filename
Definition
io.h:16
Generated by
1.9.8