• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

C is there a function like sizeof that can be used at run time not compile time?

Onceler

Golden Member
I am trying to make a program that reads several (lets say eight) bytes from a file into an array but what if there is only a few bytes left (lets say three)?
Is an array the best option for doing this and if so how do I do a sizeof to determine how many bytes are left in the file.
I am using C not C++ but is there a way to do it in either language and which one should I be using? I don't like OOP.
I will be reading from the file into long long int or hex.
 
No, there is no runtime type information available in compiled C code. You either need to know the size of the buffer at compile time, or you need to calculate it at runtime. In terms of knowing how much data was read from a file into a buffer, it depends on which method you're using to read it. To know how much data is left in the file, you could get the size before reading it, offsetting for any header information or whatnot, and then look at the file pointer. Typically a program doesn't really need to know how much data is left in a file; it just needs to know how much was read, so it knows where in the input buffer the valid data ends.
 
With respect to the datafile, the OS/language may provide to you s way to know the size of the file in advance.
 
The point is to not know the file size in advance so that it can be used on many different files.
 
I Googled for this. Then I discovered that the first solution, fseek and ftell, is apparently wrong!

The right solution appears to be stat or _stat, depending on your OS. You may need a 64-bit variant depending on your file sizes.
 
I am trying to make a program that reads several (lets say eight) bytes from a file into an array but what if there is only a few bytes left (lets say three)?
It's fine to overread a file. If there are only three bytes left, read()/fread() will return 3 instead of 8.

But if you want to know the file size for some other reason, stat(), fstat(), or lstat() will get the job done (on Linux).
 
Back
Top