From b600369367193c867013d6ac56aa3e750b66f6be Mon Sep 17 00:00:00 2001 From: kdx Date: Thu, 19 Jan 2023 03:17:08 +0100 Subject: initial commit --- .gitignore | 2 ++ Makefile | 32 ++++++++++++++++++++++++++++++++ drain.c | 28 ++++++++++++++++++++++++++++ drain.h | 4 ++++ main.c | 25 +++++++++++++++++++++++++ 5 files changed, 91 insertions(+) create mode 100644 .gitignore create mode 100644 Makefile create mode 100644 drain.c create mode 100644 drain.h create mode 100644 main.c diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..b2a8745 --- /dev/null +++ b/.gitignore @@ -0,0 +1,2 @@ +restruct +*.o diff --git a/Makefile b/Makefile new file mode 100644 index 0000000..c4f2d14 --- /dev/null +++ b/Makefile @@ -0,0 +1,32 @@ +CC := gcc +LD := $(CC) +SRC := $(wildcard *.c) +OBJ := $(patsubst %.c,%.o,$(patsubst %.cpp,%.o,$(SRC))) +NAME := restruct +CFLAGS := -Wall -Wextra -std=c99 -pedantic +LDFLAGS := + +all: $(NAME) + +$(NAME): $(OBJ) + @printf '[ld] *.o -> %s\n' "$(NAME)" + @$(LD) -o $(NAME) $(OBJ) $(LDFLAGS) + +%.o: %.c + @printf '[cc] %s -> %s\n' "$<" "$@" + @$(CC) $(CFLAGS) -c -o $@ $< + +clean: + @printf '[rm]\n' + @rm -rf $(NAME) $(OBJ) + +run: $(NAME) + @printf '[run]\n' + @./$(NAME) + +re: + @printf '[re]\n' + @make --no-print-directory clean + @make --no-print-directory + +.PHONY: all clean run re diff --git a/drain.c b/drain.c new file mode 100644 index 0000000..40c049e --- /dev/null +++ b/drain.c @@ -0,0 +1,28 @@ +#include "drain.h" +#include +#include + +char *drain(FILE *fp) +{ + size_t size = 1025; + char *buf = calloc(1025, 1); + if (buf == NULL) { + perror("drain"); + return NULL; + } + /* Read until end of file. */ + for (;;) { + if (fread(buf + size - 1025, 1024, 1, fp) != 1) + return buf; + /* Line is longer than 1024 bytes, realloc to make space. */ + size += 1024; + char *new_buf = realloc(buf, size); + if (new_buf == NULL) { + perror("drain"); + free(buf); + return NULL; + } + buf = new_buf; + memset(buf + size - 1024, 0, 1024); + } +} diff --git a/drain.h b/drain.h new file mode 100644 index 0000000..830261a --- /dev/null +++ b/drain.h @@ -0,0 +1,4 @@ +#pragma once +#include + +char *drain(FILE *fp); diff --git a/main.c b/main.c new file mode 100644 index 0000000..2f334e9 --- /dev/null +++ b/main.c @@ -0,0 +1,25 @@ +#include "drain.h" +#include +#include + +int main(int argc, char **argv) +{ + if (argc != 2) { + fprintf(stderr, "usage: %s \n", argv[0]); + return 1; + } + FILE *fp = fopen(argv[1], "rb"); + if (fp == NULL) { + perror("main"); + return 1; + } + char *data = drain(fp); + fclose(fp); + if (data == NULL) { + fprintf(stderr, "failed to drain '%s'\n", argv[1]); + return 1; + } + printf("%s", data); + free(data); + return 0; +} -- cgit v1.2.3