Skip to main content

How to: Read and Write to a Newly Created Data File

The xtd::io::binary_writer and xtd::io::binary_reader classes are used for writing and reading data other than character strings. The following example shows how to create an empty file stream, write data to it, and read data from it.

The example creates a data file called in the current directory, creates the associated binary_writer and binary_reader objects, and uses the binary_writer object to write the integers 0 through 10 to, which leaves the file pointer at the end of the file. The binary_reader object then sets the file pointer back to the origin and reads out the specified content.


#include <fstream>
#include <xtd/xtd>

using namespace std;
using namespace xtd;
using namespace xtd::io;

class program {
inline static const ustring FILE_NAME = "";

static auto main() {
if (file::exists(FILE_NAME)) {
console::write_line("{} already exists!", FILE_NAME);

using_ (ofstream fs(FILE_NAME, ios::binary | ios::out)) {
using_ (binary_writer w(fs)) {
for (int i = 0; i < 11; i++) {

using_ (ifstream fs(FILE_NAME, ios::binary | ios::in)) {
using_ (binary_reader r(fs)) {
for (int i = 0; i < 11; i++) {


// The example creates a file named "" and writes the integers 0 through 10 to it in binary format.
// It then writes the contents of to the console with each integer on a separate line.

See also