summaryrefslogtreecommitdiff
path: root/src/fs/FileSystem.cxx
blob: 3d425d1900e69795dfc7743422b038702550c345 (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
/*
 * Copyright 2003-2017 The Music Player Daemon Project
 * http://www.musicpd.org
 *
 * 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.,
 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.
 */

#include "config.h"
#include "FileSystem.hxx"
#include "AllocatedPath.hxx"
#include "Limits.hxx"
#include "system/Error.hxx"

#include <errno.h>
#include <fcntl.h>

void
RenameFile(Path oldpath, Path newpath)
{
#ifdef _WIN32
	if (!MoveFileEx(oldpath.c_str(), newpath.c_str(),
			MOVEFILE_REPLACE_EXISTING))
		throw MakeLastError("Failed to rename file");
#else
	if (rename(oldpath.c_str(), newpath.c_str()) < 0)
		throw MakeErrno("Failed to rename file");
#endif
}

AllocatedPath
ReadLink(Path path)
{
#ifdef _WIN32
	(void)path;
	errno = EINVAL;
	return nullptr;
#else
	char buffer[MPD_PATH_MAX];
	ssize_t size = readlink(path.c_str(), buffer, MPD_PATH_MAX);
	if (size < 0)
		return nullptr;
	if (size_t(size) >= MPD_PATH_MAX) {
		errno = ENOMEM;
		return nullptr;
	}
	buffer[size] = '\0';
	return AllocatedPath::FromFS(buffer);
#endif
}

void
TruncateFile(Path path)
{
#ifdef _WIN32
	HANDLE h = CreateFile(path.c_str(), GENERIC_WRITE, 0, nullptr,
			      TRUNCATE_EXISTING, FILE_ATTRIBUTE_NORMAL,
			      nullptr);
	if (h == INVALID_HANDLE_VALUE)
		throw FormatLastError("Failed to truncate %s", path.c_str());

	CloseHandle(h);
#else
	UniqueFileDescriptor fd;
	if (!fd.Open(path.c_str(), O_WRONLY|O_TRUNC))
		throw FormatErrno("Failed to truncate %s", path.c_str());
#endif
}

void
RemoveFile(Path path)
{
#ifdef _WIN32
	if (!DeleteFile(path.c_str()))
		throw FormatLastError("Failed to delete %s", path.c_str());
#else
	if (unlink(path.c_str()) < 0)
		throw FormatErrno("Failed to delete %s", path.c_str());
#endif
}