2

I have a File variable called dir and i'm building a simple file explorer for my device. Is there a way to get a reference to dir's parent directory?

3
  • Doesn't dir.name() return dir's name with the path?
    – ocrdu
    Dec 14, 2020 at 19:18
  • Unfortunately it only returns the name
    – none none
    Dec 14, 2020 at 19:43
  • 1
    Then probably the only way is to keep a list of the directories you traversed while going to that file, or while building the directory structure from root. There may be an other way, but I don't know the SD library well enough.
    – ocrdu
    Dec 14, 2020 at 20:03

1 Answer 1

-1

I don't think there is an inbuilt function returning the parent, but you could do:

FS &file_system = SD; // pick whichever file system you use

File get_parent(File dir) {
  String dirPath = dir.path();
  int lastSlashIndex = dirPath.lastIndexOf('/');
  if (lastSlashIndex != -1) {
    String parentDirPath = dirPath.substring(0, lastSlashIndex);
    File parentDir = file_system.open(parentDirPath.c_str());
    return parentDir;
  }
  return File();
}
2
  • 1
    but there is no path function in the Arduino SD library. (and no FS type)
    – Juraj
    Aug 28, 2023 at 13:11
  • I only have esp32-S3 at hand here, and path() is available in framework-arduinoespressif32 -> FS.h, I don't know the situation for other platforms/architectures. Aug 29, 2023 at 16:25

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.