2 years, 4 months ago.

How to read a binary file till its end?

Hello all,

I have ADXL345 data in a SD card in Binary. I would like to read the whole data. Currently I could able to read only first 3 bytes. How can we read whole file?.

My code is for reading is below.

int main() {
      int readings[3] = {0, 0, 0}; 
      FILE *logFile = fopen("/sd/PCE001.bin","rb");
      if (!logFile)  
      pc.puts("FAILED TO OPEN FILE"); 
      else { 
      // reading ACC
      for (int i = 0; i<3; i++) 
      pc.printf("\r\n %i",readings[i]);}

      pc.puts("File complete"); 
Comment on this question

2 Answers

2 years, 4 months ago.

Hi Mohan. Following link will help:

Specifically from one of the posts on the above webpage:

      // example of reading a file one byte at a time
      // and display it in hex format on the terminal
      unsigned char c;                          // a single byte buffer
      FILE *fp = fopen("/sd/myfile.txt", "r");  // open the file in 'read' mode
      while (!feof(fp)){                        // while not end of file
           c=fgetc(fp);                         // get a character/byte from the file
           printf("Read from file %02x\n\r",c); // and show it in hex format
      fclose(fp);                               // close the file

Hi Mohan. Here are the details on how to work around the raised symbol error:

the code here should work:

Hello Sanjiv, Thank you for your reply. I have tried this before but getting error at feof. undefined symbol feof.

posted by Mohan gandhi Vinnakota 08 Dec 2016

Hello Sanjiv, Found the answer. <<code>> while ((c = getc(file)) != EOF) pc.putc(c); <</code>> Unfortunately , It is printing the values like below 82 0 0 0 243 255 83 0 0 0 243 255 83 0 0

I am trying show the values readable.

posted by Mohan gandhi Vinnakota 08 Dec 2016

try with

posted by Sanjiv Bhatia 08 Dec 2016
2 years, 4 months ago.

hii , ı have one questıon to you ? why do you use baudrate 921600 ? baudrate of pc is 9600? is it? and also your string size is 3 bytes. ı am not sure but maybe ıt can run so ;

int readings[8] or for(int i=0; i<length.int16_t;i++) or for(int i=0 ; i<sizeof(int16_t); i++);

Hi ibrahim. The baud rate can change to support the UART (serial controller). The baudrate of the PC may power up as a 9600 bps but can be changed to suit the application. For example, we are designing host adapter that can support 20Mbps - if the UART can support the higher data rates then you are fine to select 921600 (ie. 921k). Some of the lower cost UARTs are only able to support up to 115200 bps. For example, the < $1 USD USB UARTs.

posted by Sanjiv Bhatia 08 Dec 2016

thank you so much cause you instructed to me Sanjiv

posted by ibrahim SATOGLU 08 Dec 2016

To post an answer, please log in.