ChaniLastnamé
ChaniLastnamé

Reputation: 533

C - Read file byte by byte using fread

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

Upvotes: 11

Views: 31722

Answers (1)

Yellows
Yellows

Reputation: 723

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.

Upvotes: 6

Related Questions