Writing and reading data from files

Here we will use the `it_file` class to store some data. The program `write_it_file.cpp` looks as follows:

#include <itpp/itcomm.h>
using namespace itpp;
int main()
{
// Declare the it_file class
it_file ff;
// Open a file with the name "it_file_test.it"
ff.open("it_file_test.it");
// Create some data to put into the file
vec a = linspace(1, 20, 20);
// Put the variable a into the file. The Name("a") tells the file class
// that the next variable shall be named "a".
ff << Name("a") << a;
// Force the file to be written to disc. This is useful when performing
// iterations and ensures that the information is not stored in any cache
// memory. In this simple example it is not necessary to flush the file.
ff.flush();
// Close the file
ff.close();
// Exit program
return 0;
}
itpp::linspace
vec linspace(double from, double to, int points)
linspace (works in the same way as the MATLAB version)
Definition: specmat.cpp:106
itcomm.h
Include file for the IT++ communications module.
itpp
itpp namespace
Definition: itmex.h:37

When you run this program you will obtain a file called `it_file_test.it` in your current directory. You can read the file into Matlab/Octave to view the data by using the following commands:

itload('it_file_test.it')
figure(1); clf;
plot(a)

Note: Make sure that `$PREFIX/share/itpp` is in your Matlab/Octave path and that you run the code above from the directory where `it_file_test.it` is located (`$PREFIX` is the IT++ installation prefix; `/usr/local` by default).

The IT++ program `read_it_file.cpp` that reads the file and prints its content can look like this:

#include <itpp/itcomm.h>
using namespace itpp;
int main()
{
// Declare the it_file class
it_file ff;
// Open the file "it_file_test.it" for reading
ff.open("it_file_test.it");
// Read the variable a from the file. Put result in vector a.
vec a;
ff >> Name("a") >> a;
// Print the result
std::cout << "a = " << a << std::endl;
// Exit the program
return 0;
}

Here is the output of the program:

    a = [1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20]

Generated on Tue Aug 17 2021 10:59:15 for IT++ by Doxygen 1.9.1