forked from BlackIkeEagle/muttvcardsearch
-
Notifications
You must be signed in to change notification settings - Fork 0
/
fileutils.cpp
98 lines (79 loc) · 3.04 KB
/
fileutils.cpp
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
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
/***************************************************************************
* Copyright (C) 2013 by Torsten Flammiger *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU General Public License as published by *
* the Free Software Foundation; either version 2 of the License, or *
* (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU General Public License *
* along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "fileutils.h"
FileUtils::FileUtils()
{
}
bool FileUtils::fileExists(const string &file) {
bool exists = false;
std::ifstream f(file.c_str());
if(f) {
exists = true;
f.close();
}
return exists;
}
bool FileUtils::dirExists(const string &dir) {
struct stat st;
if(stat(dir.c_str(), &st) == 0) {
if(S_ISDIR(st.st_mode))
return true;
}
return false;
}
bool FileUtils::fileRemove(const string &file) {
if( remove ( file.c_str() ) != 0 )
return false;
return true;
}
bool FileUtils::getFileContent(const string &path, string *buffer) {
std::ifstream s;
s.open(path.c_str());
if(false == s.is_open()) {
cerr << "Unable to open file '"<< path << "'" << endl;
return false;
}
std::stringstream buf;
buf << s.rdbuf();
s.close();
*buffer = buf.str();
return true;
}
bool FileUtils::putFileContent(const std::string& path, const std::string &content) {
std::ofstream s;
s.open(path.c_str(), ios::out | ios::trunc);
if(false == s.is_open()) {
cerr << "Cant write to file '" << path << "' Unable to open!" << endl;
return false;
}
s << content;
s.close();
return true;
}
std::string FileUtils::getHomeDir() {
struct passwd *pw = getpwuid(getuid());
std::string d1(pw->pw_dir);
std::string d2(getenv("HOME"));
// if set ENV['HOME'] and it differs from the one in /etc/passwd
// then return the value from ENV['HOME'] instead from /etc/passwd
if(d2.length() > 0 && d2 != d1 && dirExists(d2))
return d2;
return d1;
}