libansilove

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

loadfile.c (1120B)


      1 /*
      2  * loadfile.c
      3  * libansilove 1.3.1
      4  * https://www.ansilove.org
      5  *
      6  * Copyright (c) 2011-2022 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  * SPDX-License-Identifier: BSD-2-Clause
     13  */
     14 
     15 #include <fcntl.h>
     16 #include <stddef.h>
     17 #include <sys/mman.h>
     18 #include <sys/stat.h>
     19 #include <unistd.h>
     20 #include "ansilove.h"
     21 
     22 int
     23 ansilove_loadfile(struct ansilove_ctx *ctx, const char *input)
     24 {
     25 	int fd;
     26 	struct stat st;
     27 
     28 	if (ctx == NULL || input == NULL) {
     29 		if (ctx)
     30 			ctx->error = ANSILOVE_INVALID_PARAM;
     31 
     32 		return -1;
     33 	}
     34 
     35 	fd = open(input, O_RDONLY);
     36 	if (fd == -1) {
     37 		ctx->error = ANSILOVE_FILE_READ_ERROR;
     38 		return -1;
     39 	}
     40 
     41 	if (fstat(fd, &st) == -1) {
     42 		ctx->error = ANSILOVE_FILE_READ_ERROR;
     43 		close(fd);
     44 		return -1;
     45 	}
     46 
     47 	ctx->maplen = ctx->length = st.st_size;
     48 
     49 	/* mmap input file into memory */
     50 	ctx->buffer = mmap(NULL, ctx->maplen, PROT_READ, MAP_PRIVATE, fd, 0);
     51 	if (ctx->buffer == MAP_FAILED) {
     52 		ctx->error = ANSILOVE_MEMORY_ERROR;
     53 		close(fd);
     54 		return -1;
     55 	}
     56 
     57 	close(fd);
     58 
     59 	return 0;
     60 }