I am wondering if this is the best way to go about solving my problem.
I know the values for particular offsets of a binary file where the information I want is held...What I want to do is jump to the offsets and then read a certain amount of bytes, starting from that location.
After using google, I have come to the conclusion that my best bet is to use fseek() to move to the position of the offset, and then to use fread() to read an amount of bytes from that position.
Am I correct in thinking this? And if so, how is best to go about doing so? i.e. how to incorporate the two together.
If I am not correct, what would you suggest I do instead?
Many thanks in advance for your help.
Matt
Edit:
I followed a tutorial on fread() and adjusted it to the following:
`#include <stdio.h>
int main()
{
FILE *f;
char buffer[11];
if (f = fopen("comm_array2.img", "rt"))
{
fread(buffer, 1, 10, f);
buffer[10] = 0;
fclose(f);
printf("first 10 characters of the file:\n%s\n", buffer);
}
return 0;
}`
So I used the file 'comm_array2.img' and read the first 10 characters from the file.
But from what I understand of it, this goes from start-of-file, I want to go from some-place-in-file (offset)
Is this making more sense?
Edit Number 2:
It appears that I was being a bit dim, and all that is needed (it would seem from my attempt) is to put the fseek() before the fread() that I have in the code above, and it seeks to that location and then reads from there.
pread()
system call. Emulate it using streams instead of file descriptors. Perhaps you write yourself a function such as:ssize_t fpread(char *buffer, size_t nbytes, size_t offset, FILE *fp);
. – Cardiopread()
instead, which does both operations at once. – Korykorzybskipread
. Tell us more about what you want and what you've tried. – Pallfseek()
, yet for reasons unknown you refuse to use it in your code or even look it up in the manual to see how it could be used. – Heydefopen("comm_array2.img", "rb")
. Thefseek()
calls may give strange results when applied to a file opened in text mode. Oh ... the flag"t"
is not recognized by the Standard: it's the absence of a"b"
that makes the file a text mode one. – Across