0

What's the right way to tell if a file is contained within a given directory, or a subdirectory thereof?

I want something like:

if ([directoryPath contains: filePath]) { // file is in directory, or in a subdirectory of directory. } 

Example:

ContainerPath: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/AppName.app

Not matching: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/Documents/db/Sample Data

Matching: /Users/sfisher/Library/Application Support/iPhone Simulator/5.1/Applications/89A57CCB-250D-4D10-B913-EA456004B431/AppName.app/Samples/1

I could convert everything to strings (including appending a "/" to the container directory) and check for a string match, but it seems there should be a built-in method for this.

2 Answers 2

1

In principle, your underlying desire is surprising impossible. A given file path may include through symbolic or hard links, making "containment" a very complicated question. These kinds of links are uncommon in iOS, but iOS is still Unix, and in Unix such things are legal.

So your real question is actually whether one path specifier (string) is contained in another. So checking the paths as strings is the correct approach.

Sign up to request clarification or add additional context in comments.

1 Comment

That was a great description of the complexity of the problem. Thanks. :)
1

I think a simple string match is the right way to do it:

if (![directoryPath hasSuffix:@"/"]) directoryPath = [directoryPath stringByAppendingString:@"/"]; if ([filePath hasPrefix:directoryPath]) { // ... } 

Note that this doesn't deal with complications introduced by symlinks, or with relative paths.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.