Reading a whole file in C
Seek to the end for the size, allocate that plus one, read it back in one call.
#include <stdio.h>
#include <stdlib.h>
char *slurp(const char *path, long *length) {
FILE *f = fopen(path, "rb");
if (f == NULL) {
return NULL;
}
fseek(f, 0, SEEK_END);
long size = ftell(f);
rewind(f);
char *buffer = (size < 0) ? NULL : malloc((size_t) size + 1);
if (buffer == NULL) {
fclose(f);
return NULL;
}
size_t read = fread(buffer, 1, (size_t) size, f);
buffer[read] = '\0';
fclose(f);
*length = (long) read;
return buffer;
}
How it works
ftellafter seeking to the end gives the length.- The extra byte is for the terminator you add yourself.
- The caller owns the buffer that comes back.
Keywords and builtins used here
FILENULLcharconstiflongreturnsize_tslurp
The run, in numbers
- Lines
- 23
- Characters to type
- 435
- Tokens
- 149
- Three-star pace
- 95 tpm
At the three-star pace of 95 tokens a minute, this run takes about 94 seconds.
Step 4 of 4 in Opening & reading, step 4 of 12 in Files & I/O.