I recently learned about storage classes in C. In particular, I was fascinated by the storage class static. Based on Haskell, I avoid the concept of passing an output buffer to a function to get the result. For example, consider the following function readfile:
#include <stdio.h>
void readfile(const char * filename, char * contents, size_t size) {
FILE * file = fopen(filename, "rb");
fread(contents, size, 1, file);
contents[size] = 0;
fclose(file);
}
There are several reasons why I don’t like this code:
- Using
voidas return type annoys me. I do not know why. He just does. - Passing the output buffer to a function seems unnatural. Mutable state is error prone.
- You do not need to pass the number of bytes to read as an input parameter to the function.
- You need to create a buffer manually and predict the file size.
- :
#include <stdio.h>
#include <malloc.h>
char * readfile(const char * filename) {
FILE * file = fopen(filename, "rb");
fseek(file, 0, SEEK_END);
size_t size = ftell(file);
fseek(file, 0, SEEK_SET);
static char * contents;
contents = malloc(size + 1);
fread(contents, size, 1, file);
fclose(file);
contents[size] = 0;
return contents;
}
, , , - readfile. . , , free , .
, contents static , , , . -, , .
, static : , , , , . static, ?
, ? , C (, ..).