2023年1月21日土曜日

C++でバイナリファイルを読む方法のメモ

バイナリファイルを一度で読みたかったので。ほかにもいろいろ方法はあると思うけど、とりあえず簡易に。

C++11以降。たぶん1バイトずつ読むので、大きいファイルだと遅いかも(知らんけど)。

#include <string> #include <iostream> #include <fstream> #include <vector> std::vector<char> readAllBinary(const std::string& fileName){ std::fstream file(fileName, std::ios::in | std::ios::binary); std::vector<char> buffer((std::istreambuf_iterator<char>(file)), std::istreambuf_iterator<char>()); file.close(); return buffer; } int main(){ std::string filePath="m_01.jp"; auto vecBuffer = readAllBinary(filePath); //ファイルの読み込みに失敗している場合サイズは0になる。 std::cout << "FileSize: " << vecBuffer.size() << std::endl; //buffer pointer char* buffdata = vecBuffer.data(); // some process return 0; }

0 件のコメント:

コメントを投稿