I'm using this block of code to read and sum up the bytes of all the text files I have on an SD card:

long get_sd_memory_taken() {
  File dir = SD.open("/");
  long sd_memory_taken;
  int c = 0;
  while (true) {
    File entry = dir.openNextFile();
    if (!entry) {
      return sd_memory_taken;
    if(strcmp(entry.name(), "SYSTEM~1") == 0) {
    if(c > 15) {
    sd_memory_taken += entry.size();

The SD card is 8GB so the number won't be larger than 8,589,934,592. The function get_sd_memory_taken() returns the number so it can be send to a phone using Bluetooth. I just checked that long can hold max 2,147,483,647, so if the SD card is filled more than that, I suppose errors are gonna appear. How can I prevent this? I was thinking of maybe using a double and put the comma maybe 5 digits to the left and send that or maybe divide the number into 10 smaller longs and send them to the phone separately. I think the former method is better but I'm not sure if it'll work. What's the best way to go about this problem where I'm trying to use as less memory as possible?

  • What Arduino (and SD lib) are you using? Apr 17, 2020 at 15:04
  • 1
    unsigned long long aka uint64_t can hold up to 9,223,372,036,854,775,807.
    – Majenko
    Apr 17, 2020 at 15:05
  • @Codebreaker007 Blue Pill, SD.h Apr 17, 2020 at 15:08
  • @Majenko I'll try that, hopefully that's the most memory-efficient way to do it Apr 17, 2020 at 15:08
  • 1
    8 bytes is all that uses. Same a double.
    – Majenko
    Apr 17, 2020 at 15:08

1 Answer 1


As SD.h includes

  #include "utility/SdFat.h"
  #include "utility/SdFatUtil.h" 

or if you use the SDfat library than this function is more efficient than going all over the place:

#include <SdFat.h>

SdFat SD; 

void ShowFreeSpace() {
  // Calculate free space (volume free clusters * blocks per clusters / 2)
  long lFreeKB = SD.vol()->freeClusterCount();
  lFreeKB *= SD.vol()->blocksPerCluster()/2;

  // Display free space
  Serial.print("Free space: ");
  Serial.println(" KB");

Your Answer

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

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