0

I am trying to read a file in c using fopen and fread. My problem is that the file has 3145728 length characters but fread is reading only 168.

my code is

#include<stdio.h>
#include<stdlib.h>

 char * readFile(char* url){
 size_t size, fileSize;
 char * buffer = 0;

 FILE *filePointer;
 filePointer = fopen(url, "r");

 if(filePointer){
    fseek(filePointer, 0, SEEK_END);
    fileSize = ftell(filePointer);
    rewind(filePointer);

    buffer = (char*) malloc(sizeof(char) * (fileSize + 1));
    
    size = fread(buffer, 1, fileSize, filePointer);

    fclose(filePointer);

    printf("%d %d ", size, fileSize);

  }

 return 0;
}


void main(){
   readFile("gc_1024x1024.raw");
 }

The output of my print command is 168 3145728

this is my raw file:

3773 ed44 80fa 3876 ef2b 69e2 3272 ed32

72ee 2667 e525 66e4 2b6f ec21 67e3 246b

e92c 75f5 246f ef12 61e2 0d5e e112 63e8

1061 e80e 5ee7 0f5f ea07 57e4 004f df09

58e8 0d5d ea00 4fdc 024f dd03 50de 024d

dc00 4ad7 0049 d404 4cd4 054b cf03 48c9

0044 c102 44bf 0646 c100 3eb7 013e b107

43b3 003a a500 359c 053c a015 4aaa 1445

a409 3693 0d39 9017 4195 143d 8c0f 3580

2142 8918 377a 1835 7717 3372 1c36 731c

PS: there is my data with 8 data in each line

The output of my print command is 168 3145728

Thank you in advance

Pravin Poudel
  • 1,433
  • 3
  • 16
  • 38
  • If this is a binary file open with `"rb"` flag, `fopen(url, "rb");` – Barmak Shemirani Nov 07 '21 at 07:13
  • Try `fopen(url, "r");` -> `fopen(url, "rb");` – n. m. could be an AI Nov 07 '21 at 07:13
  • that worked like a charm, i thought the problem was with the filehandling as i am doing it after long time. Can i ask why this is binary file and why this worked? why was it only returning only 168 when it was not considered as binary file? And yes, thank you so much – Pravin Poudel Nov 07 '21 at 07:16
  • Windows is a bit weird since in text mode it does line ending conversion and 0x1a is read as EOF. https://stackoverflow.com/questions/61833223/reading-a-file-to-memory-using-standard-c-library-windows-prematurely-identifi – Retired Ninja Nov 07 '21 at 07:25

0 Answers0