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.
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
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.
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:
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 //...