[英]OS X: How can I get path to Desktop directory on macOS?
如何將文件路徑作為macOS上的字符串獲取到Desktop目錄。 我需要在純C或一些C級框架中完成它。
如果你堅持只使用C(為什么?),那么你唯一的選擇就是使用不推薦使用的API:
#include <limits.h>
#include <CoreServices/CoreServices.h>
...
FSRef fsref;
UInt8 path[PATH_MAX];
if (FSFindFolder(kUserDomain, kDesktopFolderType, kDontCreateFolder, &fsref) == noErr &&
FSRefMakePath(&fsref, path, sizeof(path)) == noErr)
{
// Make use of path
}
如果需要CFURL
而不是路徑,則可以使用CFURLCreateFromFSRef()
而不是FSRefMakePath()
。
實際上,在研究這個時,我找到了一個我不知道的API。 顯然,你可以使用它,它顯然來自Cocoa但只使用C類型:
#include <limits.h>
#include <NSSystemDirectories.h>
char path[PATH_MAX];
NSSearchPathEnumerationState state = NSStartSearchPathEnumeration(NSDesktopDirectory, NSUserDomainMask);
while (state = NSGetNextSearchPathEnumeration(state, path))
{
// Handle path
}
API的形式是它可以返回多個結果(循環的每次迭代都有一個),但是你應該只獲得一個特定用途。 在這種情況下,您可以更改while
和if
。
請注意,使用此API,用戶域中目錄的返回路徑可能使用“〜”而不是用戶主目錄的絕對路徑。 你必須自己解決這個問題。
這是一個簡短的函數,它可以在更多基於Unix的系統上運行,而不僅僅是macOS,並返回當前用戶的桌面文件夾:
#include <limits.h>
#include <stdlib.h>
/**
* Returns the path to the current user's desktop.
*/
char *path2desktop(void) {
static char real_public_path[PATH_MAX + 1] = {0};
if (real_public_path[0])
return real_public_path;
strcpy(real_public_path, getenv("HOME"));
memcpy(real_public_path + strlen(real_public_path), "/Desktop", 8);
return real_public_path;
}
該路徑僅計算一次。
如果多次調用該函數,將返回舊結果(不是線程安全的,除非第一次調用受到保護)。
我以這種方式使用Objective-C結束了:
//
// 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;
}
而且從命令行我可以這樣執行這個程序:
./search_path_for_dir 12 1
12 - NSDesktopDirectory
1 - NSUserDomainMask
我在C中使用腳本從命令行執行此程序並檢索其輸出。
這是調用這個迷你Cocoa App的C示例:
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);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.