fs/FileSystem: add TruncateFile()

This commit is contained in:
Max Kellermann 2016-08-15 22:13:38 +02:00
parent 22a353b8e3
commit 2bca3cd247
2 changed files with 29 additions and 0 deletions

View File

@ -21,8 +21,10 @@
#include "FileSystem.hxx" #include "FileSystem.hxx"
#include "AllocatedPath.hxx" #include "AllocatedPath.hxx"
#include "Limits.hxx" #include "Limits.hxx"
#include "system/Error.hxx"
#include <errno.h> #include <errno.h>
#include <fcntl.h>
AllocatedPath AllocatedPath
ReadLink(Path path) ReadLink(Path path)
@ -44,3 +46,23 @@ ReadLink(Path path)
return AllocatedPath::FromFS(buffer); return AllocatedPath::FromFS(buffer);
#endif #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
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
}

View File

@ -104,6 +104,13 @@ StatFile(Path file, struct stat &buf, bool follow_symlinks = true)
#endif #endif
/**
* Truncate a file that exists already. Throws std::system_error on
* error.
*/
void
TruncateFile(Path path);
/** /**
* Wrapper for unlink() that uses #Path names. * Wrapper for unlink() that uses #Path names.
*/ */