# 读写文件 ## 概述 使用c_utilsæä¾›çš„全局函数,实现对文件的相关æ“作。 ## 涉åŠåŠŸèƒ½ ### include/file_ex.h æä¾›c_utilsä¸å®žçŽ°çš„æ–‡ä»¶è¯»å†™åŠŸèƒ½ã€‚ #### æè¿° 具体包括对文件内容的读写以åŠå¯¹æŒ‡å®šå—符串的查找功能。 #### 函数 | | åç§° | | -------------- | -------------- | | int | **CountStrInFile**(const std::string& fileName, const std::string& subStr, bool caseSensitive = true)<br>查看指定文件ä¸å‡ºçŽ°æŒ‡å®šå—符串的次数 | | bool | **FileExists**(const std::string& fileName)<br>检查指定文件是å¦å˜åœ¨ã€‚ | | bool | **LoadBufferFromFile**(const std::string& filePath, std::vector< char >& content)<br>从指定文件ä¸è¯»å‡ºæ•°æ®ï¼Œå˜å…¥è¾“入缓å˜åŒº(`std::vector`)对象ä¸ã€‚ | | bool | **LoadStringFromFd**(int fd, std::string& content)<br>通过文件对应的文件æè¿°ç¬¦ï¼Œä»Žä¸è¯»å–全部å—符串å˜å…¥è¾“å…¥`std::string`对象ä¸ã€‚ | | bool | **LoadStringFromFile**(const std::string& filePath, std::string& content)<br>从指定文件ä¸è¯»å‡ºå…¨éƒ¨å—符串å˜å…¥è¾“å…¥`std::string`对象ä¸ã€‚ | | bool | **SaveBufferToFile**(const std::string& filePath, const std::vector< char >& content, bool truncated = true)<br>呿Œ‡å®šæ–‡ä»¶ä¸å†™å…¥ç¼“å˜åŒº(`std::vector`)对象ä¸çš„æ•°æ®ã€‚ | | bool | **SaveStringToFd**(int fd, const std::string& content)<br>通过文件对应的文件æè¿°ç¬¦ï¼Œå‘其写入å—符串。 | | bool | **SaveStringToFile**(const std::string& filePath, const std::string& content, bool truncated = true)<br>å°†å—符串写入指定文件ä¸ã€‚ | | bool | **StringExistsInFile**(const std::string& fileName, const std::string& subStr, bool caseSensitive = true)<br>æ£€æŸ¥æŒ‡å®šæ–‡ä»¶ä¸æ˜¯å¦åŒ…嫿Œ‡å®šå—符串 | ## 使用示例 1. 测试用例编译è¿è¡Œæ–¹æ³• - 测试用例代ç å‚è§ base/test/unittest/common/utils_file_test.cpp - 使用开å‘者自测试框架,使用方法å‚è§ï¼š[å¼€å‘自测试执行框架-测试用例执行](https://gitee.com/openharmony/testfwk_developer_test#%E6%B5%8B%E8%AF%95%E7%94%A8%E4%BE%8B%E6%89%A7%E8%A1%8C) - 使用以下具体命令以è¿è¡Œ`file_ex.h`对应测试用例 ```bash run -t UT -tp utils -ts UtilsFileTest ```