10

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

8
  • The os is going to buffer stuff, so measuring performance like this is not very meaningfull Feb 2, 2015 at 1:37
  • 1
    Also, *&buffer is actually the same as buffer or &buffer[0]. This is because & takes the address of the variable buffer, creating a pointer of type char**, then * dereferences that pointer, turning it back into the same char* that we started from, aka buffer.
    – RudolfW
    Feb 2, 2015 at 1:38
  • @OldProgrammer What would be a good way? I just need to measure how long it takes to read the file. Feb 2, 2015 at 1:39
  • 1
    If you're reading one byte at a time, just use getc instead of fread. fread is defined to work as if by repeated calls to getc or fgetc anyway. Feb 2, 2015 at 1:51
  • 4
    @paxdiablo: I did not say *&buffer was wrong, I just said it was about as meaningful as *&*&*&*&*&*&*&buffer of buffer+1-1. :)
    – RudolfW
    Feb 2, 2015 at 1:56

1 Answer 1

5

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.