Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- static int
- read_file(const char *filename, char **r_buf, long *r_size)
- {
- assert(r_buf != NULL);
- // attempt to open the file
- FILE *fp = fopen(filename, "r");
- if (!fp)
- spark_err_raisef(SPK_EIO, "unable to open file %s", filename);
- // determine its size
- fseek(fp, 0, SEEK_END);
- long size = ftell(fp);
- // allocate a buffer and read into
- char *data = malloc(size);
- if (!data)
- spark_err_raise(SPK_ENOMEM);
- fseek(fp, 0, SEEK_SET);
- fread(data, 1, size, fp);
- if (ferror(fp))
- spark_err_raisef(SPK_EIO, "unable to read file %s", filename);
- // return the size of file read and its contents
- if (r_size)
- *r_size = size;
- *r_buf = data;
- return 0;
- }
- int
- main(int argc, char **argv)
- {
- int err = 0;
- char *f1 = NULL;
- if ((err = read_file("ok.txt", &f1, NULL)))
- goto handle_error;
- char *f2 = NULL;
- if ((err = read_file("bad.txt", &f2, NULL)))
- goto handle_error;
- char *f3 = NULL;
- if ((err = read_file("nonexisting.txt", &f3, NULL)))
- goto handle_error;
- return 0;
- handle_error:
- fprintf(stderr, "%s\n", spark_err_msg());
- return err;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement