Created
April 19, 2018 15:07
-
-
Save yangruihan/94e697cb6ef2e682ebcf96506a58a471 to your computer and use it in GitHub Desktop.
FileHelper for cpp
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| #pragma once | |
| #include <string> | |
| namespace util | |
| { | |
| class FileUtil | |
| { | |
| public: | |
| static bool read_file(const char* file_path, std::string &result) | |
| { | |
| FILE* file = nullptr; | |
| auto errno_t = fopen_s(&file, file_path, "r+"); | |
| if (file == nullptr) | |
| { | |
| // todo log error info | |
| return false; | |
| } | |
| fseek(file, 0, SEEK_END); | |
| const size_t size = ftell(file); | |
| const auto content = new char[size]; | |
| memset(content, 0, size); | |
| rewind(file); | |
| fread(content, sizeof(char), size, file); | |
| fclose(file); | |
| result.assign(content, size); | |
| delete[] content; | |
| return true; | |
| } | |
| static bool write_file(const char* file_path, const std::string& content) | |
| { | |
| FILE* file = nullptr; | |
| auto errno_t = fopen_s(&file, file_path, "w+"); | |
| if (file == nullptr) | |
| { | |
| // todo log error info | |
| return false; | |
| } | |
| const auto content_chars = content.c_str(); | |
| fwrite(content_chars, sizeof(char), content.size(), file); | |
| fclose(file); | |
| return true; | |
| } | |
| }; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment