I have looked through the man pages, and have read a few examples on line. All my other system and standard calls seem to be working around the same data, why not fread?
#include <stdlib.h>
#include <stdio.h>
unsigned char *data;
int main(int argc, char *argv[])
{
FILE *fp = fopen("test_out.raw", "rb");
if (fp == NULL) {
fprintf(stderr, "ERROR: cannot open test_out.raw.\n");
return -1;
}
long int size;
fseek(fp, 0L, SEEK_END);
size = ftell(fp);
if(size < 0) {
fprintf(stderr, "ERROR: cannot calculate size of file.\n");
return -1;
}
data = (unsigned char *)calloc(sizeof(unsigned char), size);
if (data == NULL) {
fprintf(stderr, "ERROR: cannot create data.\n");
return -1;
}
if (!fread(data, sizeof(unsigned char), size, fp)) {
fprintf(stderr, "ERROR: could not read data into buffer.\n");
return -1;
}
int i;
for (i = 0 ; i < size; ++i) {
if (i && (i%10) == 0) putchar('\n');
fprintf(stdout, " --%c-- ", (unsigned char)(data[i]));
}
free(data);
fclose(fp);
return 0;
}
You moved to the end of the file with fseek, and then you're trying to read from it - but, since you are already at the end of the file, the read fails because there's nothing left to read.
Before attempting the read, get back to the beginning of file with another fseek:
fseek(fp, 0L, SEEK_SET);
or, even simpler, with a rewind:
rewind(fp);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With