Skip to content
Update cpp authored by umaumax's avatar umaumax
...@@ -1855,7 +1855,72 @@ bool IsFileExist(const std::string &filename) { ...@@ -1855,7 +1855,72 @@ bool IsFileExist(const std::string &filename) {
* ファイル/ディレクトリが存在: true * ファイル/ディレクトリが存在: true
* シンボリックリンクの場合はその参照先に依存 * シンボリックリンクの場合はその参照先に依存
### [How to read a file from disk to std::vector\<uint8\_t> in C\+\+]( https://gist.github.com/looopTools/64edd6f0be3067971e0595e1e4328cbc ) ### ファイルを読みたい
* [How to read a file from disk to std::vector\<uint8\_t> in C\+\+]( https://gist.github.com/looopTools/64edd6f0be3067971e0595e1e4328cbc )
* [c++ - How to read a binary file into a vector of unsigned chars - Stack Overflow]( https://stackoverflow.com/questions/15138353/how-to-read-a-binary-file-into-a-vector-of-unsigned-chars )
* なぜか、`std::istream_iterator`を利用すると、ファイルの読み込みサイズが小さくなってしまう現象が発生した
* `std::istreambuf_iterator`には`uint8_t`は指定できない
``` cpp
#include <fstream>
#include <iostream>
#include <iterator>
#include <vector>
std::vector<uint8_t> LoadFileGood(std::string& filepath) {
std::ifstream file(filepath, std::ios::binary);
if (file.fail()) {
return std::vector<uint8_t>();
}
file.unsetf(std::ios::skipws);
std::streampos fileSize;
file.seekg(0, std::ios::end);
fileSize = file.tellg();
file.seekg(0, std::ios::beg);
std::vector<uint8_t> vec;
vec.reserve(fileSize);
vec.insert(vec.begin(), std::istream_iterator<uint8_t>(file),
std::istream_iterator<uint8_t>());
return vec;
}
std::vector<uint8_t> LoadFileGood_istreambuf_iterator(std::string& filepath) {
std::ifstream is(filepath, std::ios::in | std::ios::binary);
std::istreambuf_iterator<char> start(is), end;
std::vector<uint8_t> content(start, end);
return content;
}
std::vector<uint8_t> LoadFileBad_istream_iterator(std::string& filepath) {
std::ifstream is(filepath, std::ios::in | std::ios::binary);
std::istream_iterator<char> start(is), end;
std::vector<uint8_t> content(start, end);
return content;
}
int main(int argc, const char* argv[]) {
std::string filepath("./main");
{
auto goodVec = LoadFileGood(filepath);
std::cout << goodVec.size() << std::endl;
}
{
auto goodVec = LoadFileGood_istreambuf_iterator(filepath);
std::cout << goodVec.size() << std::endl;
}
{
auto badVec = LoadFileBad_istream_iterator(filepath);
std::cout << badVec.size() << std::endl;
}
return 0;
}
```
### ファイルをmv(rename)する ### ファイルをmv(rename)する
... ...
......