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

#include <errno.h>
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 AllocatedPath::Null();
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 AllocatedPath::Null();
54
	if (size_t(size) >= MPD_PATH_MAX) {
55
		errno = ENOMEM;
56
		return AllocatedPath::Null();
57 58
	}
	buffer[size] = '\0';
59
	return AllocatedPath::FromFS(buffer);
60 61
#endif
}
62 63 64 65

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

	close(fd);
#endif
}
82 83 84 85

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