Skip to content

Refactor out potentially buggy fseek() call for getting file size #222

@saxbophone

Description

@saxbophone

Current code:

libsxbp/sxbp/utils.c

Lines 96 to 107 in 0b30978

/*
* private, works out and returns the size of the file referred to by the given
* file handle
*/
static size_t sxbp_get_file_size(FILE* file_handle) {
// seek to end
// NOTE: This isn't portable due to lack of meaningful support of `SEEK_END`
fseek(file_handle, 0, SEEK_END);
// get size
size_t file_size = (size_t)ftell(file_handle);
// seek to start again
fseek(file_handle, 0, SEEK_SET);

This is a generic function, provided by the library to ease reading of files into buffer objects.

Unfortunately, the current implementation makes use of fseek() using the SEEK_END argument, which according to the documentation:

Library implementations are allowed to not meaningfully support SEEK_END (therefore, code using it has no real standard portability).

This means that my current approach is non-portable, and although it appears to work on Linux, Mac and Windows, I don't want to take any chances!

Probably a solution which uses fstat() on Unix and the equivalent functions on Windows is the best approach, a lá this Stack Overflow answer: https://stackoverflow.com/a/238609/6177253

Metadata

Metadata

Assignees

No one assigned

    Labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions