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