Created
June 24, 2014 16:05
-
-
Save oguna/3da200199c7dc3826a06 to your computer and use it in GitHub Desktop.
ファイルから読み込んでstd::stringにするのと、char[]にするもののサンプル
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
| #include <iostream> | |
| #include <memory> | |
| #include <fstream> | |
| #include <string> | |
| #include <codecvt> | |
| #include <regex> | |
| using namespace std; | |
| unique_ptr<string> readToEndForString(char* filename) | |
| { | |
| ifstream infile(filename); | |
| if (infile.fail()) | |
| { | |
| cerr << "invalid file" << endl; | |
| return nullptr; | |
| } | |
| return make_unique<string>(istreambuf_iterator<char>(infile), istreambuf_iterator<char>()); | |
| } | |
| unique_ptr<char []> readToEndForArray(char *filename) | |
| { | |
| ifstream infile(filename); | |
| if (infile.fail()) | |
| { | |
| cerr << "can not open." << endl; | |
| return nullptr; | |
| } | |
| size_t fileSize = (size_t) infile.seekg(0, std::ios::end).tellg(); | |
| infile.seekg(0, std::ios::beg); | |
| unique_ptr<char []> buffer = make_unique<char []>(fileSize + 1); | |
| infile.read(buffer.get(), fileSize); | |
| buffer[fileSize + 1] = 0; | |
| return buffer; | |
| } | |
| int main() | |
| { | |
| auto a = readToEndForArray("main.cpp"); | |
| cout << a.get() << endl; | |
| return 0; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment