Objective c 如何获取和设置正确的当前路径
在我的简单命令行程序中,我尝试将字符串写入文本文件Objective c 如何获取和设置正确的当前路径,objective-c,nsstring,foundation,Objective C,Nsstring,Foundation,在我的简单命令行程序中,我尝试将字符串写入文本文件 [str writeToFile:@"myfile.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil]; 当我通过finder运行我的exec文件时,我希望“myfile.txt”被创建在与exec文件相同的文件夹中,但它是在“/users/me”中创建的 后来,我试图通过这些代码获取程序的当前路径 NSFileManager *filemgr; NSString *cur
[str writeToFile:@"myfile.txt" atomically:YES encoding:NSUTF8StringEncoding error:nil];
当我通过finder运行我的exec文件时,我希望“myfile.txt”被创建在与exec文件相同的文件夹中,但它是在“/users/me”中创建的
后来,我试图通过这些代码获取程序的当前路径
NSFileManager *filemgr;
NSString *currentpath;
filemgr = [[NSFileManager alloc] init];
currentpath = [filemgr currentDirectoryPath];
NSLog(@"Current path is : %@",current path);
我发现,无论我的exec文件位于何处,当前路径始终是“/users/me”。有没有办法获得正确的路径?您可以使用
NSFileManager
的defaultManager
方法返回的实例来操作当前路径:
NSString *currentpath = [[NSFileManager defaultManager] currentDirectoryPath];
或
您可以通过捆绑包的bundlePath
方法获取可执行文件的路径:
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];
NSString *path = [[[NSBundle mainBundle] bundlePath] stringByDeletingLastPathComponent];