How to extract filename from path

I am receiving some relative path information, and need to extract the filename (without the path or the extension). I am currently creating a File object using the given path, but when running in the debugger it hits an assertion that says I should not be passing raw strings that are not valid absolute paths. But I don’t see any other way to easily strip out the path information, other than to use the File object to do so. I don’t ever do anything with that File object. I just use it to get the filename. The String class does not provide that ability, as far as I can see. Is there a better way to strip out the path and extension?

If the string you’re constructing the filepath from is relative, you should tell the File object you’re creating what the path is relative to. EG:

const juce::String relativePath{ "../../temp/file.txt" };
const auto file = juce::File::getCurrentWorkingDirectory().getChildFile(relativePath);

Even if there’s not where the actual file is, if you just need to get the filename with file.getFileNameWithoutExtension() that would allow you to easily create the File object.

Ok, I think that’s what the comments around the assert mentioned, but I had assumed that was only if you were referring to an actual file. Works like a charm, thanks!

Seems the string path manipulation shouldn’t require a File object, though. The code for getting the path or the filename from a path string doesn’t really depend on anything in the actual file system, just pre-defined separators (depending on platform). Seems to me that they could be String member functions just as easily. Or static File members that take a raw string.

They could be, but I guess that’s just a design choice by the devs. You could always extract the code to your own helper functions if you wanted a cleaner way to do it.

A file object in juce is a just a string for its path. Until you reach a method that actually works with the fs, any path modification method is just a cross platform way to manipulate that path string