Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C - Read file byte by byte using fread

Tags:

c

file-io

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

like image 362
ChaniLastnamé Avatar asked Feb 02 '15 01:02

ChaniLastnamé


People also ask

How many bytes fread read?

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.

What does fread () do in C?

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.

What does fread () return in C?

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.


1 Answers

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.

like image 103
Yellows Avatar answered Oct 02 '22 04:10

Yellows