Skip to content

Commit

Permalink
Add basic c support
Browse files Browse the repository at this point in the history
  • Loading branch information
alexg-axis committed Nov 24, 2021
1 parent 24306fc commit d33761b
Show file tree
Hide file tree
Showing 4 changed files with 66 additions and 0 deletions.
15 changes: 15 additions & 0 deletions 2020/1/main.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
#include <stdio.h>
#include <stdlib.h>

#include "../../utils/c/input.h"

int main(int argc, char **argv) {
input_t input = read_input();
if (input == NULL) {
return EXIT_FAILURE;
}

printf("%s\n", input);
free(input);
return EXIT_SUCCESS;
}
5 changes: 5 additions & 0 deletions scripts/run.sh
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@ fi
main_files="$(find "$year/$day" -depth 1 -iname "main*")"
for file in $main_files; do
name="$(basename "$file")"
directory="$(dirname "$file")"
case "${name##*.}" in
"go")
go run "$file"
Expand All @@ -33,6 +34,10 @@ for file in $main_files; do
export PYTHONPATH="$PWD/utils/python/:$PYTHONPATH"
python3 "$file"
;;
"c")
out="$(mktemp --suffix=.main)"
gcc -o "$out" "$directory/"*.c utils/c/*.c && "$out"
;;
*)
echo "unsupported $file"
esac
Expand Down
34 changes: 34 additions & 0 deletions utils/c/input.c
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
#include <libgen.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#include "input.h"

input_t read_input_impl(char *main_file) {
char *directory = dirname(main_file);

size_t directory_length = strlen(directory);

// Room for the directory, a slash, input.txt and a null byte
size_t path_length = path_length + 1 + 9 + 1;
char *input_path = (char *)malloc(path_length);
if (input_path == NULL) {
return NULL;
}
strncpy(input_path, directory, path_length);
strncpy(input_path + directory_length, "/input.txt", path_length);
input_path[path_length - 1] = 0;

FILE *file = fopen(input_path, "r");
fseek(file, 0, SEEK_END);
size_t file_size = ftell(file);
fseek(file, 0, SEEK_SET);

char *input = malloc(file_size + 1);
fread(input, sizeof(char), file_size, file);
fclose(file);
input[file_size] = 0;

return (input_t)input;
}
12 changes: 12 additions & 0 deletions utils/c/input.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
#ifndef __INPUT_H__
#define __INPUT_H__

#include <stdlib.h>

typedef char* input_t;

#define read_input() read_input_impl(__FILE__)

input_t read_input_impl(char *main_file);

#endif

0 comments on commit d33761b

Please sign in to comment.