blob: 03c22b0d03ea156c5b4e679f487c5bceb66cce51 (
plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
|
#ifndef _FILELIB_H_
#define _FILELIB_H_
#include <cassert>
#include <string>
#include <iostream>
#include <cstdlib>
#include "gzstream.h"
bool FileExists(const std::string& file_name);
bool DirectoryExists(const std::string& dir_name);
// reads from standard in if filename is -
// uncompresses if file ends with .gz
// otherwise, reads from a normal file
class ReadFile {
public:
ReadFile(const std::string& filename) :
no_delete_on_exit_(filename == "-"),
in_(no_delete_on_exit_ ? static_cast<std::istream*>(&std::cin) :
(EndsWith(filename, ".gz") ?
static_cast<std::istream*>(new igzstream(filename.c_str())) :
static_cast<std::istream*>(new std::ifstream(filename.c_str())))) {
if (!no_delete_on_exit_ && !FileExists(filename)) {
std::cerr << "File does not exist: " << filename << std::endl;
abort();
}
if (!*in_) {
std::cerr << "Failed to open " << filename << std::endl;
abort();
}
}
~ReadFile() {
if (!no_delete_on_exit_) delete in_;
}
inline std::istream* stream() { return in_; }
private:
static bool EndsWith(const std::string& f, const std::string& suf) {
return (f.size() > suf.size()) && (f.rfind(suf) == f.size() - suf.size());
}
const bool no_delete_on_exit_;
std::istream* const in_;
};
class WriteFile {
public:
WriteFile(const std::string& filename) :
no_delete_on_exit_(filename == "-"),
out_(no_delete_on_exit_ ? static_cast<std::ostream*>(&std::cout) :
(EndsWith(filename, ".gz") ?
static_cast<std::ostream*>(new ogzstream(filename.c_str())) :
static_cast<std::ostream*>(new std::ofstream(filename.c_str())))) {}
~WriteFile() {
(*out_) << std::flush;
if (!no_delete_on_exit_) delete out_;
}
inline std::ostream* stream() { return out_; }
private:
static bool EndsWith(const std::string& f, const std::string& suf) {
return (f.size() > suf.size()) && (f.rfind(suf) == f.size() - suf.size());
}
const bool no_delete_on_exit_;
std::ostream* const out_;
};
#endif
|