add input functions

This commit is contained in:
Evan Burkey 2021-12-10 12:41:36 -08:00
parent d564364686
commit 12363f0ed6
5 changed files with 115 additions and 0 deletions

3
.gitignore vendored
View File

@ -1 +1,4 @@
cmake* cmake*
.cache
build
compile_commands.json

View File

@ -1,5 +1,6 @@
cmake_minimum_required(VERSION 3.17) cmake_minimum_required(VERSION 3.17)
project(flint C) project(flint C)
set(CMAKE_EXPORT_COMPILE_COMMANDS ON)
set(CMAKE_C_STANDARD 99) set(CMAKE_C_STANDARD 99)
include_directories(include) include_directories(include)
@ -9,6 +10,7 @@ set(SOURCES
src/set.c src/set.c
src/stack.c src/stack.c
src/binarytree.c src/binarytree.c
src/input.c
) )
add_library(flint ${SOURCES}) add_library(flint ${SOURCES})

8
build.sh Executable file
View File

@ -0,0 +1,8 @@
#!/bin/sh -e
mkdir -p build
cd build
cmake ..
make
cp compile_commands.json ..
cd

13
include/input.h Normal file
View File

@ -0,0 +1,13 @@
#ifndef LIBFLINT_INPUT_H
#define LIBFLINT_INPUT_H
#include <stdlib.h>
char *get_input(const char *);
char **split(const char *, size_t *, const char *);
char **get_lines(const char *, size_t *);
int *get_ints(const char *, size_t *);
void del_split(char **);
void del_lines(char **);
#endif // LIBFLINT_INPUT_H

89
src/input.c Normal file
View File

@ -0,0 +1,89 @@
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <limits.h>
#ifdef __linux__
#include <bsd/stdlib.h>
#endif
#include "input.h"
char *get_input(const char *path) {
FILE *fp = NULL;
fp = fopen(path, "r");
if (fp == NULL) {
fprintf(stderr, "Failed to open %s. Returning NULL\n", path);
return NULL;
}
fseek(fp, 0, SEEK_END);
size_t fsz = ftell(fp);
rewind(fp);
char* buf = NULL;
buf = malloc(fsz + 1);
if (buf == NULL) {
fprintf(stderr, "Failed to malloc buf. Returning NULL\n");
fclose(fp);
return NULL;
}
fread(buf, 1, fsz, fp);
buf[fsz] = '\0';
fclose(fp);
return buf;
}
char **split(const char *s, size_t *lsz, const char *delim) {
char **lines = NULL;
char *t = strtok(s, delim);
size_t n = 0;
while (t != NULL) {
lines = realloc(lines, sizeof(char *) * ++n);
if (lines == NULL) {
fprintf(stderr, "Failed to realloc lines buffer. Returning NULL\n");
free(s);
return NULL;
}
lines[n - 1] = t;
t = strtok(NULL, delim);
}
*lsz = n;
return lines;
}
char **get_lines(const char *path, size_t *lsz) {
return split(get_input(path), lsz, "\n");
}
int *get_ints(const char *path, size_t *sz) {
char **lines = get_lines(path, sz);
int *i = malloc(sizeof(int) * *sz);
for (size_t idx = 0; idx < *sz; idx++) {
int n;
const char *errstr;
n = strtonum(lines[idx], INT_MIN, INT_MAX, &errstr);
if (errstr) {
printf("Failed to convert %s to int. Returning NULL\n", lines[idx]);
exit(1);
}
i[idx] = n;
}
del_lines(lines);
return i;
}
void del_split(char **sp) {
free(sp[0]);
free(sp);
}
void del_lines(char **lines) {
del_split(lines);
}