OS X:如何获取macOS上Desktop目录的路径? [英] OS X: How can I get path to Desktop directory on macOS?

查看:385
本文介绍了OS X:如何获取macOS上Desktop目录的路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何在macOS上以字符串的形式获取Desktop目录的文件路径. 我需要在纯C或某些C级框架中完成.

How can I get file path to Desktop directory as a string on macOS. I need it to be done in pure C or with some C-level framework.

推荐答案

我以这样的方式结束了对Objective-C的使用:

I ended with usage of Objective-C in such way:

//
//  main.m
//  search_path_for_dir
//
//  Created by Michal Ziobro on 23/09/2016.
//  Copyright © 2016 Michal Ziobro. All rights reserved.
//

#import <Foundation/Foundation.h>

int main(int argc, const char * argv[]) {
    if(argc != 3)
        return 1;

    @autoreleasepool {
        NSArray *paths = NSSearchPathForDirectoriesInDomains(atoi(argv[1]), atoi(argv[2]), YES);
        NSString *path = [paths objectAtIndex:0];
        [path writeToFile:@"/dev/stdout" atomically:NO encoding:NSUTF8StringEncoding error:nil];
    }
    return 0;
}

并且从命令行我可以通过以下方式执行该程序:

And than from command line I can execute this program in that way:

./search_path_for_dir 12 1 

12-NSDesktopDirectory

1-NSUserDomainMask

我在C中使用脚本,该脚本从命令行执行此程序并检索其输出.

I am using script in C that executes this program from command line and retrieves its output.

这里是C示例,称为此迷你Cocoa App:

Here's C example calling this mini Cocoa App:

CFStringRef FSGetFilePath(int directory, int domainMask) {

    CFStringRef scheme = CFSTR("file:///");
    CFStringRef absolutePath = FSGetAbsolutePath(directory, domainMask);

    CFMutableStringRef filePath = CFStringCreateMutable(NULL, 0);
    if (filePath) {

        CFStringAppend(filePath, scheme);
        CFStringAppend(filePath, absolutePath);

    }

    CFRelease(scheme);
    CFRelease(absolutePath);

    return filePath;
}

CFStringRef FSGetAbsolutePath(int directory, int domainMask) {

    char path_cmd[BUF_SIZE];
    sprintf(path_cmd, "./tools/search_path_for_dir %d %d", directory, domainMask);
    char *path = exec_cmd(path_cmd);

    return CFStringCreateWithCString(kCFAllocatorDefault, path, kCFStringEncodingUTF8);
}

这篇关于OS X:如何获取macOS上Desktop目录的路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆