xtd 0.2.0
file_info_replace.cpp

Show how to use xtd::io::file_info::replace method.

#include <xtd/io/file>
#include <xtd/io/file_info>
#include <xtd/console>
#include <xtd/startup>
using namespace xtd;
using namespace xtd::io;
class program {
public:
static auto main() {
try {
// original_file and file_to_replace must contain the path to files that already exist in the
// file system. backup_of_file_to_replace is created during the execution of the Replace method.
auto original_file = "test.txt"_s;
auto file_to_replace = "test2.txt"_s;
auto backup_of_file_to_replace = "test2.txt.bak"_s;
if (file::exists(original_file) && file::exists(file_to_replace)) {
console::write_line("Move the contents of " + original_file + " into " + file_to_replace + ", delete " + original_file + ", and create a backup of " + file_to_replace + ".");
// Replace the file.
replace_file(original_file, file_to_replace, backup_of_file_to_replace);
} else
console::write_line("Either the file {0} or {1} doesn't exist.", original_file, file_to_replace);
} catch (const system_exception& e) {
console::write_line(e.message());
}
}
// Move a file into another file, delete the original, and create a backup of the replaced file.
static void replace_file(const string& file_to_move_and_delete, const string& file_to_replace, const string& backup_of_file_to_replace) {
// Create a new file_info object.
auto f_info = file_info {file_to_move_and_delete};
// replace the file.
f_info.replace(file_to_replace, backup_of_file_to_replace);
}
};
startup_(program::main);
// This code produces the following output :
//
// Move the contents of test.txt into test2.txt, delete test.txt, and create a backup of test2.txt.
// Done
static console_key_info read_key()
Obtains the next character or function key pressed by the user. The pressed key is displayed in the c...
static void write_line()
Writes the current line terminator to the standard output stream using the specified format informati...
Provides static methods for the creation, copying, deletion, moving, and opening of files,...
Definition file_info.hpp:41
file_info replace(const xtd::string &destination_file_name, const xtd::string &destination_backup_file_name)
Replaces the contents of a specified file with the file described by the current xtd::io::file_info o...
static bool exists(const xtd::string &path) noexcept
Determines whether the specified file exists.
The exception that is thrown when a method call is invalid for the object's current state.
Definition system_exception.hpp:18
#define startup_(main_method)
Defines the entry point to be called when the application loads. Generally this is set either to the ...
Definition startup.hpp:167
@ e
The E key.
Definition console_key.hpp:96
The xtd::io namespace contains types that allow reading and writing to files and data streams,...
Definition binary_reader.hpp:17
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition abstract_object.hpp:8