0

Is the following the correct way to get the number of bytes in a file? Are there more straightforward ways, perhaps directly from the FILE* object?

size_t
num_bytes(FILE *fp)
{
    fseek(fp, 0, SEEK_END);
    return (size_t) ftell(fp);
}

Additionally, why does ftell return a long int and not a size_t object? I find it a bit difficult to figure out which "size-ish" functions return size_t and which don't. Is there a good way to remember that? Or is the reason that ftell isn't size_t because it uses -1L as the "fail value" ?

samuelbrody1249
  • 4,379
  • 1
  • 15
  • 58
  • Well, it couldn't return `size_t` because I believe it throws -1 on error. However, I'm not sure why it couldn't use `ssize_t` (Just saw your edit and that you mentioned the possibility too) – mediocrevegetable1 Feb 17 '21 at 03:51
  • It's signed so that negative values can give an error. – M.M Feb 17 '21 at 03:51
  • @mediocrevegetable1 `ssize_t` is not a Standard C type – M.M Feb 17 '21 at 03:51
  • @M.M Ah, ok. That makes sense. – mediocrevegetable1 Feb 17 '21 at 03:52
  • 1
    `size_t` only needs to be large enough to support *in-memory* objects, but files are not in-memory. Think about 32-bit systems where `sizeof(size_t) == 4` but those systems can still have 100GB-sized files on-disk, and `size_t` is too small to represent that. (FAT’s 2GB file size limit does not apply to NTFS, etc) – Dai Feb 17 '21 at 03:57

0 Answers0