stumped
stumped

Reputation: 3293

Confused on creating new directories and changing directories (Objective-C)

When I changed the current directory path of main.m to newDir why does it still say that there are no files in newDir? Also I ran this program multiple times with no errors. Does that mean I ended up creating multiple newDir?

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    @autoreleasepool {
        NSString *newDir = @"newDir";
        NSFileManager *manager = [NSFileManager defaultManager];

        if ([manager createDirectoryAtPath:newDir withIntermediateDirectories:YES attributes:nil error:NULL] == NO) {
            NSLog(@"couldnt create new directory");
            return 1;
        }

        if ([manager changeCurrentDirectoryPath: newDir] == NO) {
            NSLog(@"couldnt change directory path");
            return 2;
        }

        NSLog(@"%@", [manager currentDirectoryPath]);
        NSLog(@"%@", [manager contentsOfDirectoryAtPath:newDir error:NULL]);
    }
    return 0;
}

Output:

2012-08-07 10:27:20.428 Test[853:707] /Users/ss/Library/Developer/Xcode/DerivedData/Test-bfrqtnrhaafmdzghoyirjnfqjbfc/Build/Products/Debug/newDir
2012-08-07 10:36:47.832 Test[885:707] (null)

Upvotes: 1

Views: 124

Answers (2)

Hot Licks
Hot Licks

Reputation: 47729

Since you're ignoring errors on your contentsOfDirectoryAtPath call, it's entirely possible that the call is failing -- hence the null.

Without looking at references, it appears that you're looking for directory .../newDir/newDir, a directory that likely does not exist.

In any event, since newDir is new it wouldn't contain any entries (other than . and ..).

Upvotes: 1

Sergey Kalinichenko
Sergey Kalinichenko

Reputation: 726629

The path to main.m does not play into what happens when you run your program: the only question is whether the directory has any files or not, and from the log it appears that it doesn't.

To create some files in the directory, run these commands in the terminal window:

touch /Users/ss/Library/Developer/Xcode/DerivedData/Test-bfrqtnrhaafmdzghoyirjnfqjbfc/Build/Products/Debug/newDir/quick.txt
touch /Users/ss/Library/Developer/Xcode/DerivedData/Test-bfrqtnrhaafmdzghoyirjnfqjbfc/Build/Products/Debug/newDir/brown.txt
touch /Users/ss/Library/Developer/Xcode/DerivedData/Test-bfrqtnrhaafmdzghoyirjnfqjbfc/Build/Products/Debug/newDir/fox.txt

This will create three empty files. Now run your program, and see if it discovers the newly created txt files; it should.

On your second question, the operating system would not let you create multiple file system objects with identical names, so the answer is no, you created only one newDir.

Upvotes: 1

Related Questions