1# 获取用户目录环境(C/C++) 2 3## 场景介绍 4 5[Environment](../reference/apis-core-file-kit/_environment.md)提供了获取公共文件用户目录路径的能力,以支持三方应用在公共文件用户目录下进行文件访问操作。 6 7## 约束限制 8 9- 使用此接口,需确认设备具有以下系统能力:SystemCapability.FileManagement.File.Environment.FolderObtain。 10- 此接口仅用作公共沙箱目录路径的获取接口,操作对应的公共目录及其子目录需获取通过弹窗授权方式向用户申请授予对应目录的权限,具体参考[访问控制-向用户申请授权](../security/AccessToken/request-user-authorization.md) 11 12## 接口说明 13 14接口的详细说明,请参考[API参考](../reference/apis-core-file-kit/_environment.md) 15 16| 接口名称 | 描述 | 17| -------- | -------- | 18| FileManagement_ErrCode OH_Environment_GetUserDownloadDir (char **result)| 获取用户Download目录沙箱路径。只支持2in1设备 | 19| FileManagement_ErrCode OH_Environment_GetUserDesktopDir (char **result) | 获取用户Desktop目录沙箱路径。只支持2in1设备 | 20| FileManagement_ErrCode OH_Environment_GetUserDocumentDir (char **result) | 获取用户Document目录沙箱路径。只支持2in1设备 | 21 22## 开发步骤 23 24**在CMake脚本中链接动态库** 25 26CMakeLists.txt中添加以下lib。 27 28```txt 29target_link_libraries(sample PUBLIC libohenvironment.so) 30``` 31 32**添加头文件** 33 34```c++ 35#include <filemanagement/environment/oh_environment.h> 36#include <filemanagement/fileio/oh_fileio.h> 37``` 38 391. 调用OH_Environment_GetUserDownloadDir接口获取用户Download目录沙箱路径,在接口中使用malloc申请的内存需要在使用完后释放因此需要free对应的内存。示例代码如下所示: 40 41 ```c 42 void GetUserDownloadDirPathExample() { 43 char *downloadPath = NULL; 44 FileManagement_ErrCode ret = OH_Environment_GetUserDownloadDir(&downloadPath); 45 if (ret == 0) { 46 printf("Download Path=%s", downloadPath); 47 free(downloadPath); 48 } else { 49 printf("GetDownloadPath failed, error code is %d", ret); 50 } 51 } 52 ``` 53 542. 调用OH_Environment_GetUserDesktopDir接口获取用户Desktop目录沙箱路径,在接口中使用malloc申请的内存需要在使用完后释放因此需要free对应的内存。示例代码如下所示: 55 56 ```c 57 void GetUserDesktopDirPathExample() { 58 char *desktopPath = NULL; 59 FileManagement_ErrCode ret = OH_Environment_GetUserDesktopDir(&desktopPath); 60 if (ret == 0) { 61 printf("Desktop Path=%s", desktopPath); 62 free(desktopPath); 63 } else { 64 printf("GetDesktopPath failed, error code is %d", ret); 65 } 66 } 67 ``` 68 693. 调用OH_Environment_GetUserDocumentDir接口获取用户Document目录沙箱路径,在接口中使用malloc申请的内存需要在使用完后释放因此需要free对应的内存。示例代码如下所示: 70 71 ```c 72 void GetUserDocumentDirPathExample() { 73 char *documentPath = NULL; 74 FileManagement_ErrCode ret = OH_Environment_GetUserDocumentDir(&documentPath); 75 if (ret == 0) { 76 printf("Document Path=%s", documentPath); 77 free(documentPath); 78 } else { 79 printf("GetDocumentPath failed, error code is %d", ret); 80 } 81 } 82 ``` 83