libansilove

Library for converting ANSI, ASCII, and other formats to PNG
Log | Files | Refs | README | LICENSE

loadfile.c (1070B)


      1 /*
      2  * loadfile.c
      3  * libansilove 1.2.7
      4  * https://www.ansilove.org
      5  *
      6  * Copyright (c) 2011-2020 Stefan Vogt, Brian Cassidy, and Frederic Cambus
      7  * All rights reserved.
      8  *
      9  * libansilove is licensed under the BSD 2-Clause License.
     10  * See LICENSE file for details.
     11  */
     12 
     13 #include <fcntl.h>
     14 #include <stddef.h>
     15 #include <sys/mman.h>
     16 #include <sys/stat.h>
     17 #include <unistd.h>
     18 #include "ansilove.h"
     19 
     20 int
     21 ansilove_loadfile(struct ansilove_ctx *ctx, char *input)
     22 {
     23 	int fd;
     24 	struct stat st;
     25 
     26 	if (ctx == NULL || input == NULL) {
     27 		if (ctx)
     28 			ctx->error = ANSILOVE_INVALID_PARAM;
     29 
     30 		return -1;
     31 	}
     32 
     33 	fd = open(input, O_RDONLY);
     34 	if (fd == -1) {
     35 		ctx->error = ANSILOVE_FILE_READ_ERROR;
     36 		return -1;
     37 	}
     38 
     39 	if (fstat(fd, &st) == -1) {
     40 		ctx->error = ANSILOVE_FILE_READ_ERROR;
     41 		close(fd);
     42 		return -1;
     43 	}
     44 
     45 	ctx->maplen = ctx->length = st.st_size;
     46 
     47 	/* mmap input file into memory */
     48 	ctx->buffer = mmap(NULL, ctx->maplen, PROT_READ, MAP_PRIVATE, fd, 0);
     49 	if (ctx->buffer == MAP_FAILED) {
     50 		ctx->error = ANSILOVE_MEMORY_ERROR;
     51 		close(fd);
     52 		return -1;
     53 	}
     54 
     55 	close(fd);
     56 
     57 	return 0;
     58 }