在Cocoa中查找文件的上次访问日期

Ami*_*Sri 6 cocoa objective-c

是否可以使用cocoa在mac中获取文件/文件夹最后访问日期?

    struct stat output;
    //int ret = stat([[[openPanel filenames] lastObject] UTF8String], &output);
    int ret = stat([[[openPanel filenames] lastObject] fileSystemRepresentation], &output);
    // error handling omitted for this example
    struct timespec accessTime = output.st_atimespec;

    NSDate *aDate = [NSDate dateWithTimeIntervalSince1970:accessTime.tv_sec];

    NSLog(@"Access Time %d, %@",ret, aDate);
Run Code Online (Sandbox Code Playgroud)

根据上面的代码,我尝试了UTF8String和fileSystemRepresentation,但两者都给了我当前的日期和时间.如果我做错了,请告诉我.

Jer*_*myP 11

使用stat系统调用的C方式将在Objective-C中工作.

例如

struct stat output;
int ret = stat(aFilePath, &output);
// error handling omitted for this example
struct timespec accessTime = output.st_atime;
Run Code Online (Sandbox Code Playgroud)

您应该通过将-fileSystemRepresentation发送到包含该路径的NSString来获取aFilePath.

另一种可能获得所需内容的方法是在指向所需文件的文件URL之前构造NSURL,并使用-resourceValuesForKeys:error:获取NSURLContentAccessDate资源值.

  • @Peter Hosey:不要使用UTF8String来获取C字符串,使用filseSystemRepresentation,正如我在答案中所述. (2认同)