|
- #define new(type) (type*)malloc(sizeof(type))
-
- 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(NULL, 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 = NULL;
- FILE *fp = fopen(filename, "r");
- if (fp != NULL) {
- /* 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));
-
- /* Read the entire file into memory. */
- size_t newLen = fread(fileContent, sizeof(char), bufsize, fp);
- if ( ferror( fp ) != 0 ) {
- fputs("Error reading file", stderr);
- }
- }
- closeFile:
- fclose(fp);
- }
-
- return fileContent;
- /* Don't forget to call free() later! */
- }
|