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

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.
Last edited on
I presume you mean "only a few bytes left" in the file.

You could take a look at fread() where you can request a certain number of bytes to be read, and the return value tells you how many bytes were actually read.

http://www.cplusplus.com/reference/cstdio/fread/
The fread return value approach is one way.

Also if you want to know the size of a file, the typical way with the std library is to seek to the end, do a tell, then seek back to the beginning:

1
2
3
4
5
6
7
8
int filesize;
FILE* f = fopen("yourfile","rb");

fseek(f,0,SEEK_END);  // seek to the end
filesize = ftell(f);   // 'tell' to find out our current position (ie:  the file size)
fseek(f,0,SEEK_SET);  // seek back to beginning

//... 


Of course this will only work properly if the file is open in binary mode, since text mode translates line breaks as they're read, messing with the file size.
Thank you so much for the replies, I will study this.
When you say "array", it makes me think you are reading your data into a char array and then converting the array into a number. You should be able to go directly to the number:
1
2
int x;
int result = fread(&x, sizeof(x), 1, myFile);


At least, a similar approach can be done with C++ "std::ifstream.read()".

I also wonder about your variable lengths of file. Typically, the data you read from a file (in binary mode particularly) is data that you wrote in a specific pattern. To know when that pattern breaks, you can put an unsigned before the pattern to signify the amount of data in the pattern.
1
2
3
4
5
6
7
4 Bytes :  Amount of People
  (one for each Item)
  4 Bytes : Id of person
  4 Bytes : length of name
    1 Byte   : one for each letter in name
  4 Bytes : Age of person
4 Bytes : Amount of Other things //... 
Last edited on
I would like to keep it long long int avoiding the array if possible and the filesize would not be known at compile time.
It might help to clarify the question if you could provide a sample of the file data, and state how it should be interpreted by the program,
Topic archived. No new replies allowed.