我正在关注" Objective-C第四版中的编程"作者:Stephen Kochan。
该程序查找文件,并在其上执行一些操作:
#import <Foundation/Foundation.h>
int main(int argc, const char * argv[]) {
@autoreleasepool {
NSString *fName = @"testfile";
NSFileManager *fm;
NSDictionary *attr;
//Need to create an instance of the file manager
fm = [NSFileManager defaultManager];
//Let's make sure our test file exists first
NSLog([fm currentDirectoryPath]);
if ([fm fileExistsAtPath: fName] == NO) {
NSLog(@"File doesn't exist!");
return 1;
}
//now lets make a copy
if ([fm copyItemAtPath: fName toPath: @"newfile" error: NULL]) {
NSLog(@"File Copy failed!");
return 2;
}
//Now let's see test to see if the two files are equal
if ([fm contentsEqualAtPath: fName andPath: @"newfile"] == NO) {
NSLog(@"Files are Not Equal!");
return 3;
}
//Now lets rename the copy
if ([fm moveItemAtPath: @"newfile" toPath: @"newfile2" error: NULL] == NO) {
NSLog(@"File rename Failed");
return 4;
}
//get the size of the newfile2
if((attr = [fm attributesOfItemAtPath: @"newfile2" error: NULL]) == nil)
{
NSLog(@"Couldn't get file attributes");
return 5;
}
NSLog(@"File size is %llu bytes", [[attr objectForKey: NSFileSize] unsignedLongLongValue]);
//And finally, let's delete the original file
if([fm removeItemAtPath: fName error: NULL])
{
NSLog(@"file removal failed");
return 6;
}
NSLog(@"All operations were successful");
//Display the contents of the newly-createed file
NSLog(@" %@", [NSString stringWithContentsOfFile: @"newfile2" encoding:NSUTF8StringEncoding error: NULL]);
}
return 0;
}
我创建了一个名为&#34; testfile&#34;的文件。并将其放在项目目录中。当我运行程序时,它无法找到该文件。我添加[NSFileManager currentDirectoryPath]来检查当前路径,显然是这样的:
/Users/myusername/Library/Developer/Xcode/DerivedData/Prog_16.1-eekphhgfzdjviqauolqexkowfqfg/Build/Products/Debug
我去寻找图书馆目录,但它并不存在。这是程序运行时创建的临时目录,然后在退出后删除吗?
编辑:我尝试使用[NSFileManager changeCurrentDirectoryPath:newPath]更改当前目录的路径,但无法更改路径。我尝试将newPath设置为@&#34; Users / username / Desktop&#34;那也失败了!
答案 0 :(得分:1)
Library目录确实存在,但它作为标准隐藏。打开终端并输入命令:chflags nohidden~ / Library /。
再看一遍,它会神奇地存在!
编辑:对于使用NSFileManager编程,有一个非常有用的功能:NSSearchPathForDirectoriesInDomains()。例如。要获取桌面目录:
NSString *path = [[NSSearchPathForDirectoriesInDomains(NSDesktopDirectory, NSUserDomainMask, YES) lastObject] stringByAppendingPathComponent:@"test.txt"];
NSString *test = @"hello";
[test writeToFile:path atomicallly:YES];
这会将一个小的txt文件写入桌面。 (只要你的app不是沙盒)。
希望这会有所帮助。
答案 1 :(得分:0)
当您将文件放在项目目录中时,它会作为应用程序包的一部分发送。要获取包目录树,请使用NSBundle
...
// use the file extension (if any) for the ofType: param
NSString *path = [[NSBundle mainBundle] pathForResource:@"testfile" ofType:@""];
if ([[NSFileManager defaultManager] fileExistsAtPath:path]) {
NSLog(@"there it is! %@", path);
}