FileSystem.cxx 2.27 KB
Newer Older
1
/*
Max Kellermann's avatar
Max Kellermann committed
2
 * Copyright 2003-2020 The Music Player Daemon Project
3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20
 * 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 "FileSystem.hxx"
21
#include "AllocatedPath.hxx"
22
#include "Limits.hxx"
23
#include "system/Error.hxx"
24

Rosen Penev's avatar
Rosen Penev committed
25 26
#include <cerrno>

27
#include <fcntl.h>
28

29 30 31
void
RenameFile(Path oldpath, Path newpath)
{
32
#ifdef _WIN32
33 34 35 36 37 38 39 40 41
	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
}

42 43
AllocatedPath
ReadLink(Path path)
44
{
45
#ifdef _WIN32
46 47
	(void)path;
	errno = EINVAL;
48
	return nullptr;
49 50 51
#else
	char buffer[MPD_PATH_MAX];
	ssize_t size = readlink(path.c_str(), buffer, MPD_PATH_MAX);
52
	if (size < 0)
53
		return nullptr;
54
	if (size_t(size) >= MPD_PATH_MAX) {
55
		errno = ENOMEM;
56
		return nullptr;
57
	}
58
	return AllocatedPath::FromFS(std::string_view{buffer, size_t(size)});
59 60
#endif
}
61 62 63 64

void
TruncateFile(Path path)
{
65
#ifdef _WIN32
66 67 68 69 70 71 72 73
	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
74 75
	UniqueFileDescriptor fd;
	if (!fd.Open(path.c_str(), O_WRONLY|O_TRUNC))
76 77 78
		throw FormatErrno("Failed to truncate %s", path.c_str());
#endif
}
79 80 81 82

void
RemoveFile(Path path)
{
83
#ifdef _WIN32
84 85 86 87 88 89 90
	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
}