Advertisement
Guest User

Untitled

a guest
Sep 3rd, 2015
68
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C 1.09 KB | None | 0 0
  1. static int
  2. read_file(const char *filename, char **r_buf, long *r_size)
  3. {
  4.     assert(r_buf != NULL);
  5.  
  6.     // attempt to open the file
  7.     FILE *fp = fopen(filename, "r");
  8.     if (!fp)
  9.         spark_err_raisef(SPK_EIO, "unable to open file %s", filename);
  10.  
  11.     // determine its size
  12.     fseek(fp, 0, SEEK_END);
  13.     long size = ftell(fp);
  14.  
  15.     // allocate a buffer and read into
  16.     char *data = malloc(size);
  17.     if (!data)
  18.         spark_err_raise(SPK_ENOMEM);
  19.     fseek(fp, 0, SEEK_SET);
  20.     fread(data, 1, size, fp);
  21.     if (ferror(fp))
  22.         spark_err_raisef(SPK_EIO, "unable to read file %s", filename);
  23.  
  24.     // return the size of file read and its contents
  25.     if (r_size)
  26.         *r_size = size;
  27.     *r_buf = data;
  28.  
  29.     return 0;
  30. }
  31.  
  32. int
  33. main(int argc, char **argv)
  34. {
  35.     int err = 0;
  36.  
  37.     char *f1 = NULL;
  38.     if ((err = read_file("ok.txt", &f1, NULL)))
  39.         goto handle_error;
  40.  
  41.     char *f2 = NULL;
  42.     if ((err = read_file("bad.txt", &f2, NULL)))
  43.         goto handle_error;
  44.  
  45.     char *f3 = NULL;
  46.     if ((err = read_file("nonexisting.txt", &f3, NULL)))
  47.         goto handle_error;
  48.  
  49.     return 0;
  50.  
  51. handle_error:
  52.     fprintf(stderr, "%s\n", spark_err_msg());
  53.     return err;
  54. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement