Admittedly this is probably not the best way to do it
Indeed. You want the system to provide you an easy-to-use ‘maximum name length’ constant but the system’s position is that it won’t provide such a value because best practice is to deal with arbitrary name lengths.
Another reason why we are interested in the max file name is that we
want to be able to append a postfix to the file name … but if the
constant is wrong we could end up making too long of a name which
fails the system call.
Again, this isn’t best practice. As you’re aware, different volume formats have different lengths, which means the system can’t express this concept as a constant. If you’re extending a name like this, you have to do it in the context of a specific volume.
You can get volume-specific values here — see _PC_NAME_MAX
and _PC_PATH_MAX
in the pathconf
man page — but I think you’ll find that these are also unsatisfactory. There’s a fundamental issue in play, which is that the text encoding used by the BSD APIs, UTF-8, doesn’t line up with the text encoding used by the volume format. So these APIs could reasonably return a value that is the maximum length of a name that the file system can hold, but that doesn’t guarantee that you can create every possible name of that length.
This is an extension of the name validation problem. Every volume format has its own constraints as to what represents a valid name and it’s hard to export those constraints in a way that’s useful to clients. Imagine an API that’s able to express the limits of:
-
APFS, with 255 Unicode characters, except for slash
-
HFS Plus, with 255 UTF-16 elements, except for colon [1]
-
HFS, with 31 bytes of some retro Mac text encoding which is set by the user per volume, again except for colon
-
MS-DOS/FAT, with an 8.3 name using a very limited set of characters
That’d be one hella complex API, so complex that it probably wouldn’t be useful to clients. Clients would simply fall back to “let’s create the file and see if it fails” algorithm, which is what the Finder does btw, and that’s how we got to where we are (-:
Share and Enjoy
—
Quinn “The Eskimo!” @ Developer Technical Support @ Apple
let myEmail = "eskimo" + "1" + "@" + "apple.com"
[1] When we introduced Mac OS X, we flipped the colon and slash limitation twice:
-
On the volume, we disallowed colon.
-
At the BSD level, we flipped this to disallow slash.
-
At higher level, we flipped it again to disallow colon.