1 //===- FuzzerIO.cpp - IO utils. -------------------------------------------===// 2 // 3 // The LLVM Compiler Infrastructure 4 // 5 // This file is distributed under the University of Illinois Open Source 6 // License. See LICENSE.TXT for details. 7 // 8 //===----------------------------------------------------------------------===// 9 // IO functions. 10 //===----------------------------------------------------------------------===// 11 #include "FuzzerInternal.h" 12 #include <iostream> 13 #include <iterator> 14 #include <fstream> 15 #include <dirent.h> 16 namespace fuzzer { 17 18 static std::vector<std::string> ListFilesInDir(const std::string &Dir) { 19 std::vector<std::string> V; 20 DIR *D = opendir(Dir.c_str()); 21 if (!D) return V; 22 while (auto E = readdir(D)) { 23 if (E->d_type == DT_REG || E->d_type == DT_LNK) 24 V.push_back(E->d_name); 25 } 26 closedir(D); 27 return V; 28 } 29 30 Unit FileToVector(const std::string &Path) { 31 std::ifstream T(Path); 32 return Unit((std::istreambuf_iterator<char>(T)), 33 std::istreambuf_iterator<char>()); 34 } 35 36 std::string FileToString(const std::string &Path) { 37 std::ifstream T(Path); 38 return std::string((std::istreambuf_iterator<char>(T)), 39 std::istreambuf_iterator<char>()); 40 } 41 42 void CopyFileToErr(const std::string &Path) { 43 std::ifstream T(Path); 44 std::copy(std::istreambuf_iterator<char>(T), std::istreambuf_iterator<char>(), 45 std::ostream_iterator<char>(std::cerr, "")); 46 } 47 48 void WriteToFile(const Unit &U, const std::string &Path) { 49 std::ofstream OF(Path); 50 OF.write((const char*)U.data(), U.size()); 51 } 52 53 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V) { 54 for (auto &X : ListFilesInDir(Path)) 55 V->push_back(FileToVector(DirPlusFile(Path, X))); 56 } 57 58 std::string DirPlusFile(const std::string &DirPath, 59 const std::string &FileName) { 60 return DirPath + "/" + FileName; 61 } 62 63 } // namespace fuzzer 64