blob: ef23d42ea53a5110fa44de550e9e560feb60030c [file] [log] [blame]
Aaron Ballmanef116982015-01-29 16:58:29 +00001//===- 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"
Kostya Serebryany5b266a82015-02-04 19:10:20 +000012#include <iostream>
13#include <iterator>
Aaron Ballmanef116982015-01-29 16:58:29 +000014#include <fstream>
15#include <dirent.h>
16namespace fuzzer {
17
18static 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
30Unit 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
Kostya Serebryany52a788e2015-03-31 20:13:20 +000036std::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
Kostya Serebryany5b266a82015-02-04 19:10:20 +000042void 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
Aaron Ballmanef116982015-01-29 16:58:29 +000048void WriteToFile(const Unit &U, const std::string &Path) {
49 std::ofstream OF(Path);
50 OF.write((const char*)U.data(), U.size());
51}
52
53void ReadDirToVectorOfUnits(const char *Path, std::vector<Unit> *V) {
54 for (auto &X : ListFilesInDir(Path))
55 V->push_back(FileToVector(DirPlusFile(Path, X)));
56}
57
58std::string DirPlusFile(const std::string &DirPath,
59 const std::string &FileName) {
60 return DirPath + "/" + FileName;
61}
62
63} // namespace fuzzer