Back
Syntax
Study
Editor
Mode:
HTML
CSS
JavaScript
PHP
Reset
Run »
HTML / CSS / JS
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <errno.h> /* Read entire file into a malloc\'d buffer (caller must free) */ char *read_file(const char *path, long *out_size) { char *buf = NULL; FILE *f = NULL; long size = 0; f = fopen(path, "rb"); if (!f) { fprintf(stderr, "fopen '%s': %s ", path, strerror(errno)); goto done; } if (fseek(f, 0, SEEK_END) != 0) { perror("fseek"); goto done; } size = ftell(f); if (size < 0) { perror("ftell"); goto done; } rewind(f); buf = malloc((size_t)size + 1); if (!buf) { perror("malloc"); goto done; } size_t got = fread(buf, 1, (size_t)size, f); if ((long)got != size && ferror(f)) { perror("fread"); free(buf); buf = NULL; goto done; } buf[got] = '\0'; /* null-terminate for text use */ if (out_size) *out_size = (long)got; done: if (f) fclose(f); return buf; } int main(void) { /* Write a test file first */ FILE *f = fopen("test.txt", "w"); if (f) { fprintf(f, "Line one Line two Line three "); fclose(f); } long sz; char *content = read_file("test.txt", &sz); if (content) { printf("Read %ld bytes: %s ", sz, content); free(content); } /* Demonstrate error path */ char *missing = read_file("no_such_file.txt", NULL); if (!missing) printf("Correctly handled missing file. "); return EXIT_SUCCESS; }
Result
Open