diff --git a/include/common.h b/include/common.h new file mode 100644 index 0000000..befa1ce --- /dev/null +++ b/include/common.h @@ -0,0 +1,24 @@ +#ifndef COMMON_H +#define COMMON_H + +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include +#include + +#define IS_ALPHA(c) ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z')) +#define IS_DIGIT(c) (c >= '0' && c <= '9') +#define IS_ALNUM(c) (IS_ALPHA(c) || IS_DIGIT(c)) +#define IS_PUNCT(c) ((c >= 33 && c <= 47) || (c >= 58 && c <= 64) || (c >= 91 && c <= 96) || (c >= 123 && c <= 126)) + +char* get_file_content(char*); +char* get_file_content_with_size(char*, size_t*); + +#endif // COMMON_H \ No newline at end of file diff --git a/src/common.c b/src/common.c new file mode 100644 index 0000000..a4622b9 --- /dev/null +++ b/src/common.c @@ -0,0 +1,43 @@ +#include "common.h" + +char* get_file_content(char* path) { + if (!path) return NULL; + + FILE* file = fopen(path, "rb"); + if (!file) { perror("ERROR: could not open file in get_file_content!"); return NULL; } + if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return NULL; } + long file_size = ftell(file); + if (file_size < 0) { perror("ERROR: file size is negative in get_file_content!"); fclose(file); return NULL; } + if (fseek(file, 0, SEEK_SET) != 0) { fclose(file); return NULL; } + size_t n = (size_t)file_size; + char* buf = (char*)calloc(n + 1, 1); + if (!buf) { fclose(file); return NULL; } + + size_t got = fread(buf, 1, n, file); + fclose(file); + + buf[got] = '\0'; + + return buf; +} + +char* get_file_content_with_size(char* path, size_t* size) { + if (!path || !size) return NULL; + + FILE* file = fopen(path, "rb"); + if (!file) { perror("ERROR: could not open file in get_file_content_with_size!"); return NULL; } + if (fseek(file, 0, SEEK_END) != 0) { fclose(file); return NULL; } + long file_size = ftell(file); + if (file_size < 0) { perror("ERROR: file size is negative in get_file_content_with_size!"); fclose(file); return NULL; } + if (fseek(file, 0, SEEK_SET) != 0) { fclose(file); return NULL; } + size_t n = (size_t)file_size; + + char* buf = (char*)malloc(n); + if (!buf) { fclose(file); return NULL; } + + size_t got = fread(buf, 1, n, file); + fclose(file); + + *size = got; + return buf; +} \ No newline at end of file