I wrote the functions for opening a file, getting a file size and getting a file contents. I would welcome any suggestions to improve my code.
You might think I'm over-commenting the code. But I do it mostly just for the visual separation of the code parts. I hope to know your opinion about it.
P. S. English isn't my native language, but I try to write all code comments in English. So I would welcome any corrections also!
/*
===============
open_file
===============
*/
FILE *open_file(char const * restrict name, char const * restrict mode) {
/* Debug: checking the input arguments. */
assert(name != NULL);
assert(mode != NULL);
/* Opening the file and checking if an error occurs. */
FILE *file = fopen(name, mode);
if (file == NULL) {
LOG("Error: the file \"%s\" couldn't be opened (in the \"%s\" mode). "
"The reason: \"%s\".\n", name, mode, strerror(errno));
}
return file;
}
/*
===============
get_file_size
===============
*/
long get_file_size(FILE *file) {
/* Debug: checking the input arguments. */
assert(file != NULL);
/* Setting the file position to the ending of the file. */
fseek(file, 0, SEEK_END);
/* Getting the size of the file. */
const long size = ftell(file);
if (size == -1) {
LOG("Error: can't get the current value of the file position. The "
"reason: \"%s\".\n", strerror(errno));
}
/* Setting the file position to the beginning of the file. */
rewind(file);
return size;
}
/*
===============
get_file_contents
===============
*/
char *get_file_contents(FILE *file) {
/* Debug: checking the input arguments. */
assert(file != NULL);
/* Getting the size of the file. */
long const size = get_file_size(file);
if (size == -1)
return NULL;
/* Allocating memory for the contents of the file. */
char * const contents = calloc(size + 1, 1);
if (contents == NULL) {
LOG("Error: can't allocate %ld bytes for a contents of a file. "
"The reason: \"%s\".\n", size, strerror(errno));
}
/* Reading the contents of the file and checking if an error occurs. */
size_t const read_size = fread(contents, 1, size, file);
if (read_size < (size_t) size) {
LOG("Warning: the size of elements successfully read (%zu bytes) is "
"less than the size of the file (%ld bytes). It also may occurs "
"if the file uses the CR+LF line endings (it is the Microsoft "
"Windows system usually).\n", read_size, size);
}
return contents;
}