tags:

views:

3370

answers:

4

If I want to allocate a char array (in C) that is guaranteed to be large enough to hold any valid absolute path+filename, how big does it need to be.

On Win32, there is the MAX_PATH define. What is the equivalent for Unix/linux?

+5  A: 

Well, on Linux at least, there is:

  • PATH_MAX (defined in limits.h)

  • FILENAME_MAX (defined in stdio.h)

both of these are set to 4096 on my system (x86 Linux).

Update: : Some info from the glibc manual on this

Each of the following macros is defined in limits.h only if the system has a fixed, uniform limit for the parameter in question. If the system allows different file systems or files to have different limits, then the macro is undefined; use pathconf or fpathconf to find out the limit that applies to a particular file

AndrewR
That looks like a portability no-no.
Tom
I suppose the maximum could vary depending on the filesystem type you're using, which would imply a runtime check, not a compile-time constant.
AndrewR
+4  A: 

You can use pathconf() to figure out at run-time, but there's also a PATH_MAX preprocessor define in <limits.h>.

unwind
+12  A: 

There is a PATH_MAX but it is a bit problematic. According to 'man realpath' description:

Never use this function. It is broken by design since it is impossible to determine a suitable size for the output buffer. According to POSIX a buffer of size PATH_MAX suf­ fices, but PATH_MAX need not be a defined constant, and may have to be obtained using pathconf(). And asking pathconf() does not really help, since on the one hand POSIX warns that the result of pathconf() may be huge and unsuitable for mallocing memory. And on the other hand pathconf() may return -1 to signify that PATH_MAX is not bounded.

stefanB
+6  A: 

The other answers so far all seem right on point about the *nix side of things, but I'll add a warning about it on Windows.

You've been lied to (by omission) by the documentation.

MAX_PATH is indeed defined, and probably even applies to files stored on FAT or FAT32. However, any path name can be prefixed by \\.\ to tell the Windows API to ignore MAX_PATH and let the file system driver make up its own mind. After that, the definitions get fuzzy.

Add to the mix the fact that path names are actually Unicode (well, UTS-16) and that when the "ANSI" API is used the conversion to and from the internal Unicode name is dependent on a bunch of factors including the current code page, and you have a recipe for confusion.

A good description of the rules for Windows is at MSDN.

RBerteig