25개 이상의 토픽을 선택하실 수 없습니다. Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 
 

72 lines
1.9 KiB

  1. #define new(type) (type*)malloc(sizeof(type))
  2. int string_equal(char* a, char* b) {
  3. return !strcmp(a, b);
  4. }
  5. // asprintf implementation
  6. int _vscprintf_so(const char * format, va_list pargs) {
  7. int retval;
  8. va_list argcopy;
  9. va_copy(argcopy, pargs);
  10. retval = vsnprintf(NULL, 0, format, argcopy);
  11. va_end(argcopy);
  12. return retval;
  13. }
  14. int vasprintf(char **strp, const char *fmt, va_list ap) {
  15. int len = _vscprintf_so(fmt, ap);
  16. if (len == -1) return -1;
  17. char *str = malloc((size_t) len + 1);
  18. if (!str) return -1;
  19. int r = vsnprintf(str, len + 1, fmt, ap); /* "secure" version of vsprintf */
  20. if (r == -1) return free(str), -1;
  21. *strp = str;
  22. return r;
  23. }
  24. int asprintf(char *strp[], const char *fmt, ...) {
  25. va_list ap;
  26. va_start(ap, fmt);
  27. int r = vasprintf(strp, fmt, ap);
  28. va_end(ap);
  29. return r;
  30. }
  31. // asprintf implementation end
  32. char* read_entire_file (char* filename) {
  33. char *fileContent = NULL;
  34. FILE *fp = fopen(filename, "r");
  35. if (fp != NULL) {
  36. /* Go to the end of the file. */
  37. if (fseek(fp, 0L, SEEK_END) == 0) {
  38. /* Get the size of the file. */
  39. long bufsize = ftell(fp);
  40. if (bufsize == -1) {
  41. fputs("Empty file", stderr);
  42. goto closeFile;
  43. }
  44. /* Go back to the start of the file. */
  45. if (fseek(fp, 0L, SEEK_SET) != 0) {
  46. fputs("Error reading file", stderr);
  47. goto closeFile;
  48. }
  49. /* Allocate our buffer to that size. */
  50. fileContent = malloc(sizeof(char) * (bufsize));
  51. /* Read the entire file into memory. */
  52. size_t newLen = fread(fileContent, sizeof(char), bufsize, fp);
  53. if ( ferror( fp ) != 0 ) {
  54. fputs("Error reading file", stderr);
  55. }
  56. }
  57. closeFile:
  58. fclose(fp);
  59. }
  60. return fileContent;
  61. /* Don't forget to call free() later! */
  62. }