I am trying to read a file byte by byte (this is important because I have to measure performance). I can't seem to get the fread to work properly. Right now it just gives me the last byte of the file.
This is what I have:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main(int argc, char **argv) {
FILE *fileptr;
char *buffer;
long filelen;
int i;
fileptr = fopen(argv[1], "rb");
fseek(fileptr, 0, SEEK_END);
filelen = ftell(fileptr);
rewind(fileptr);
buffer = (char *)malloc((filelen+1)*sizeof(char));
for(i = 0; i < filelen; i++) {
fread(*&buffer, 1, 1, fileptr);
}
printf("File len: %ld\n", filelen);
printf("%s\n",*&buffer);
fclose(fileptr); // Close the file
return 0;
}
Any help is appreciated
bin','w'); fwrite(fileID,[1:9]); fclose(fileID); Read all the data in the file into a vector of class double . By default, fread reads a file 1 byte at a time, interprets each byte as an 8-bit unsigned integer ( uint8 ), and returns a double array.
The fread() function returns the number of full items successfully read, which can be less than count if an error occurs, or if the end-of-file is met before reaching count. If size or count is 0, the fread() function returns zero, and the contents of the array and the state of the stream remain unchanged.
fread returns the number of full items actually read, which may be less than count if an error occurs or if the end of the file is encountered before reaching count . Use the feof or ferror function to distinguish a read error from an end-of-file condition.
You need to advance the pointer:
for(i = 0; i < filelen; i++) {
fread(buffer+i, 1, 1, fileptr);
}
Currently, at every iteration the loop overwrites the previous character. No surprise then that only the last character appears.
By the way, you should add a '\0' character after the loop, which will mark the end of the string, so that printf()
will stop printing after it.
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