-
Notifications
You must be signed in to change notification settings - Fork 1
/
file.h
70 lines (63 loc) · 1.43 KB
/
file.h
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
/*
Copyright (c) 2012-2014 The SSDB Authors. All rights reserved.
Use of this source code is governed by a BSD-style license that can be
found in the LICENSE file.
*/
#ifndef UTIL_FILE_H_
#define UTIL_FILE_H_
#include <sys/types.h>
#include <sys/stat.h>
#include <unistd.h>
#include <string>
static inline
bool file_exists(const std::string &filename){
struct stat st;
return stat(filename.c_str(), &st) == 0;
}
static inline
bool is_dir(const std::string &filename){
struct stat st;
if(stat(filename.c_str(), &st) == -1){
return false;
}
return (bool)S_ISDIR(st.st_mode);
}
static inline
bool is_file(const std::string &filename){
struct stat st;
if(stat(filename.c_str(), &st) == -1){
return false;
}
return (bool)S_ISREG(st.st_mode);
}
// return number of bytes read
static inline
int file_get_contents(const std::string &filename, std::string *content){
char buf[8192];
FILE *fp = fopen(filename.c_str(), "rb");
if(!fp){
return -1;
}
int ret = 0;
while(!feof(fp) && !ferror(fp)){
int n = fread(buf, 1, sizeof(buf), fp);
if(n > 0){
ret += n;
content->append(buf, n);
}
}
fclose(fp);
return ret;
}
// return number of bytes written
static inline
int file_put_contents(const std::string &filename, const std::string &content){
FILE *fp = fopen(filename.c_str(), "wb");
if(!fp){
return -1;
}
int ret = fwrite(content.data(), 1, content.size(), fp);
fclose(fp);
return ret == (int)content.size()? ret : -1;
}
#endif