xtd 0.2.0
Loading...
Searching...
No Matches
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);
console::write_line("Done");
} 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());
}
console::read_key();
}
// 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
basic_string replace(value_type old_char, value_type new_char) const noexcept
Replaces all occurrences of a specified char_t in this basic_string with another specified char_t.
Definition basic_string.h:1647
Provides static methods for the creation, copying, deletion, moving, and opening of files,...
Definition file_info.h:41
The exception that is thrown when a method call is invalid for the object's current state.
Definition system_exception.h: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.h:175
The xtd::io namespace contains types that allow reading and writing to files and data streams,...
Definition binary_reader.h:16
The xtd namespace contains all fundamental classes to access Hardware, Os, System,...
Definition xtd_about_box.h:10