libpulsar
A modular compiler for the pulsar programming language
Loading...
Searching...
No Matches
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
7void ps_file_ctx_init(struct ps_file_ctx* file_ctx, STR filename, char* buffer,
9 file_ctx->filename = filename;
10 file_ctx->buffer = buffer;
11 file_ctx->length = length;
12}
13
14char* 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}
#define STR
Definition def.h:40
#define isize
Definition def.h:49
#define usize
Definition def.h:50
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
char * ps_read_file_safe(const char *filename, isize *length_ext)
Definition io.c:14
Defines safe file I/O functions.
char buffer[ITOA_BUFFER_SIZE]
Definition itoa.c:11
static void usize length
Definition lexer.h:71
Information captured in a file necessary for effective info/error reporting.
Definition io.h:15
usize length
Definition io.h:18
char * buffer
Definition io.h:17
STR filename
Definition io.h:16