summaryrefslogtreecommitdiff
path: root/tools/file.c
blob: 22835006228b25ed2b8940ccc0ed4a3f74d55162 (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
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
#include "tools/file.h"

#include <sys/stat.h>
#include <string.h>
#include <unistd.h>
#include <fcntl.h>
#include <errno.h>

cTBFile::cTBFile(void) {
}

cTBFile::~cTBFile() {
	Close();
}

bool cTBFile::Open(const cTBString &Filename, int Mode, mode_t Attribs) {
	int filed;

	if (IsOpen()) Close();

	if ((filed = ::open(Filename, Mode, Attribs)) == -1)
		return false;

	if (!cTBSource::Open(filed))
		return false;

	m_Filename = Filename;
	m_Anonymous = false;
	return true;
}

bool cTBFile::Open(uint Fileno) {
	if (IsOpen()) Close();

	if (!cTBSource::Open(Fileno))
		return false;

	m_Filename.Format("<&%d>", Fileno);
	m_Anonymous = true;
	return true;
}

bool cTBFile::Close(void) {
	bool ret = true;

	if (!IsOpen())
		ERRNUL(EBADF);

	if (::close(*this) == -1)
		ret = false;

	if (!cTBSource::Close())
		ret = false;

	m_Filename.Clear();
	return ret;
}

bool cTBFile::Unlink(void) const {
	if (m_Filename.IsNull())
		ERRNUL(ENOENT);

	if (!IsOpen())
		ERRNUL(EBADF);

	if (m_Anonymous)
		ERRNUL(EINVAL);

	return cTBFile::Unlink(m_Filename);
}

bool cTBFile::Unlink(const cTBString &Filename) {
	return (::unlink(Filename) != -1);
}

ssize_t cTBFile::Size(void) const {
	struct stat buf;
	
	if (!IsOpen())
		ERRSYS(EBADF);

	if (fstat(*this, &buf) == -1)
		return -1;

	return buf.st_size;
}

ssize_t cTBFile::Size(const cTBString &Filename) {
	struct stat buf;
	
	if (stat(Filename, &buf) == -1)
		return -1;

	return buf.st_size;
}