172540c46031f4eacc274d5ad9d89384fa1a393c
[oota-llvm.git] / lib / Fuzzer / FuzzerIO.cpp
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 <fstream>
13 #include <dirent.h>
14 namespace fuzzer {
15
16 std::vector<std::string> ListFilesInDir(const std::string &Dir) {
17   std::vector<std::string> V;
18   DIR *D = opendir(Dir.c_str());
19   if (!D) return V;
20   while (auto E = readdir(D)) {
21     if (E->d_type == DT_REG || E->d_type == DT_LNK)
22       V.push_back(E->d_name);
23   }
24   closedir(D);
25   return V;
26 }
27
28 Unit FileToVector(const std::string &Path) {
29   std::ifstream T(Path);
30   return Unit((std::istreambuf_iterator<char>(T)),
31               std::istreambuf_iterator<char>());
32 }
33
34 void WriteToFile(const Unit &U, const std::string &Path) {
35   std::ofstream OF(Path);
36   OF.write((const char*)U.data(), U.size());
37 }
38
39 void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V) {
40   for (auto &X : ListFilesInDir(Path))
41     V->push_back(FileToVector(std::string(Path) + "/" + X));
42 }
43
44 }  // namespace fuzzer