mpd/test/WriteFile.cxx

57 lines
1016 B
C++
Raw Permalink Normal View History

// SPDX-License-Identifier: GPL-2.0-or-later
// Copyright The Music Player Daemon Project
2015-01-06 19:22:04 +01:00
2021-12-03 14:02:07 +01:00
#include "io/FileOutputStream.hxx"
#include "fs/NarrowPath.hxx"
2018-07-17 21:56:43 +02:00
#include "util/PrintException.hxx"
2015-01-06 19:22:04 +01:00
#include <cerrno>
2015-01-06 19:22:04 +01:00
#include <unistd.h>
2015-01-06 19:22:04 +01:00
#include <string.h>
#include <stdlib.h>
#include <stdio.h>
2015-01-06 19:22:04 +01:00
static bool
Copy(OutputStream &dest, int src)
{
while (true) {
2023-05-15 11:00:21 +02:00
std::byte buffer[8192];
2015-01-06 19:22:04 +01:00
ssize_t nbytes = read(src, buffer, sizeof(buffer));
if (nbytes < 0) {
fprintf(stderr, "Failed to read from stdin: %s\n",
strerror(errno));
return false;
}
if (nbytes == 0)
return true;
2023-05-15 11:00:21 +02:00
dest.Write(std::span{buffer}.first(nbytes));
2015-01-06 19:22:04 +01:00
}
}
int
main(int argc, char **argv)
2018-07-17 21:56:43 +02:00
try {
2015-01-06 19:22:04 +01:00
if (argc != 2) {
fprintf(stderr, "Usage: WriteFile PATH\n");
return EXIT_FAILURE;
}
const FromNarrowPath path = argv[1];
2015-01-06 19:22:04 +01:00
2018-07-17 21:56:43 +02:00
FileOutputStream fos(path);
2015-01-06 19:22:04 +01:00
2018-07-17 21:56:43 +02:00
if (!Copy(fos, STDIN_FILENO))
return EXIT_FAILURE;
2015-01-06 19:22:04 +01:00
2018-07-17 21:56:43 +02:00
fos.Commit();
2018-07-17 21:56:43 +02:00
return EXIT_SUCCESS;
} catch (...) {
PrintException(std::current_exception());
return EXIT_FAILURE;
2015-01-06 19:22:04 +01:00
}