This function receives the main.c binary file path in the command line parameter, then reads the contents of this file, puts it into the buffer character array, adds the terminator ” at the end, converts it to a string and returns it.
static char* readFile(const char* path) {
FILE* file = fopen(path, "rb");
if (!file) {
fprintf(stderr, "Could not open file " %s ".n", path);
exit(1);
}
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);
char* buffer = (char*)malloc(sizeof(char) * (fileSize + 1));
if (!buffer) {
fprintf(stderr, "Not enought memory to read %s".n", path);
exit(1);
}
size_t bytesRead = fread(buffer, sizeof(char), fileSize, file); // ERROR!!!
if (bytesRead < fileSize) {
fprintf(stderr, "Could not read file "%s".n", path);
exit(1);
}
buffer[bytesRead] = '';
fclose(file);
return buffer;
}
Statements that cause exceptions: size_t bytesRead = fread(buffer, sizeof(char), fileSize, file);
The fread function throws an exception when reading a binary file. I tried forcing type conversion on fileSize, but it doesn’t seem to be a type problem. fileSize can correctly receive the number of bytes in the file. I really don’t know how to correct it.
10
fseek(file, 0L, SEEK_END);
size_t fileSize = ftell(file);
rewind(file);
Binary streams need not support the SEEK_END
value, and the fseek()
statement is specified as having undefined behavior in the ISO C Standard.
Don’t use fseek()
+ ftell()
to find the size of the file. Use POSIX’s stat()
/fstat()
(Yes, they’re supported by Windows too, albeit with preceding underscores), or just allocate a fixed amount of memory and realloc()
as needed until fread()
returns a short count.
If it’s a binary file, then you should expect that it may contain null bytes, and therefore you cannot rely on a null byte to indicate the end of the buffer. You need to rely on a buffer count. @Tom Karzes
Other than that, C doesn’t have exceptions. fread()
can not raise an exception.