|
- #define new(type) (type*)malloc(sizeof(type))
- #define nullptr NULL
-
- #define concat_( a, b) a##b
- #define label(prefix, lnum) concat_(prefix,lnum)
- #define try \
- if (1) \
- goto label(body,__LINE__); \
- else \
- while (1) \
- if (1) { \
- if(error) return 0; \
- break; \
- } \
- else label(body,__LINE__):
-
- typedef enum { false, true } bool;
-
- int string_equal(char* a, char* b) {
- return !strcmp(a, b);
- }
-
- // asprintf implementation
- int _vscprintf_so(const char * format, va_list pargs) {
- int retval;
- va_list argcopy;
- va_copy(argcopy, pargs);
- retval = vsnprintf(nullptr, 0, format, argcopy);
- va_end(argcopy);
- return retval;
- }
-
- int vasprintf(char **strp, const char *fmt, va_list ap) {
- int len = _vscprintf_so(fmt, ap);
- if (len == -1) return -1;
- char *str = malloc((size_t) len + 1);
- if (!str) return -1;
- int r = vsnprintf(str, len + 1, fmt, ap); /* "secure" version of vsprintf */
- if (r == -1) return free(str), -1;
- *strp = str;
- return r;
- }
-
- int asprintf(char *strp[], const char *fmt, ...) {
- va_list ap;
- va_start(ap, fmt);
- int r = vasprintf(strp, fmt, ap);
- va_end(ap);
- return r;
- }
- // asprintf implementation end
-
- char* read_entire_file (char* filename) {
- char *fileContent = nullptr;
- FILE *fp = fopen(filename, "r");
- if (fp) {
- /* Go to the end of the file. */
- if (fseek(fp, 0L, SEEK_END) == 0) {
- /* Get the size of the file. */
- long bufsize = ftell(fp);
- if (bufsize == -1) {
- fputs("Empty file", stderr);
- goto closeFile;
- }
-
- /* Go back to the start of the file. */
- if (fseek(fp, 0L, SEEK_SET) != 0) {
- fputs("Error reading file", stderr);
- goto closeFile;
- }
-
- /* Allocate our buffer to that size. */
- fileContent = malloc(sizeof(char) * (bufsize) +1);
-
- /* Read the entire file into memory. */
- size_t newLen = fread(fileContent, sizeof(char), bufsize, fp);
- fileContent[bufsize-1] = '\0';
- if ( ferror( fp ) != 0 ) {
- fputs("Error reading file", stderr);
- }
- }
- closeFile:
- fclose(fp);
- }
-
- return fileContent;
- /* Don't forget to call free() later! */
- }
-
- char* read_line() {
- char* line = malloc(100), * linep = line;
- size_t lenmax = 100, len = lenmax;
- int c;
-
- if(line == NULL)
- return NULL;
-
- for(;;) {
- c = fgetc(stdin);
- if(c == EOF)
- break;
-
- if(--len == 0) {
- len = lenmax;
- char * linen = realloc(linep, lenmax *= 2);
-
- if(linen == NULL) {
- free(linep);
- return NULL;
- }
- line = linen + (line - linep);
- linep = linen;
- }
-
- if((*line++ = c) == '\n')
- break;
- }
- *line--; // we dont want the \n actually
- *line = '\0';
- return linep;
- }
|