KADATH SPECTRAL SOLVER

Tutorial 12 : Using Files

This tutorial deals with the use of files for saving and reading results.

Writing files

The file must be open via the fopen function.

For integers and doubles one needs to use the function fwrite_be, that uses the big endian convention.

Most of Kadath classes have a function save that must be invoked. Please note that the various fields need to be constructed not only from the file but also from the Space so that this one needs to be saved first.

// Opening the file in write mode.
FILE* fout = fopen ("file.dat", "w") ;

// Two values to be saved
int valint = 2 ;
double valdouble = 1.31732 ;

// Write using fwrite_be
fwrite_be (&valint, sizeof(int), 1, fout) ;
fwrite_be (&valdouble, sizeof(double), 1, fout) ;

// Assume a space, a scalar and a vector have been previously defined
// They are saved by invoking save
space.save(fout) ;
field.save(fout) ;
vecU.save(fout) ;

// Dont forget to close the file in the end
fclose(fout) ;

Reading files

The objects in the files must obviously be read in the same order as they have been saved.

For integers and doubles, this in done using fread_be.

The various classes have constructors from a file. As said above, the constructors also need a Space so that this one must be saved first.

// Opening the file in read mode.
FILE* fin = fopen ("file.dat", "r") ;

// Two values to be read
int valint  ;
double valdouble  ;

// Read using fread_be
fread_be (&valint, sizeof(int), 1, fin) ;
fread_be (&valdouble, sizeof(double), 1, fin) ;

cout << "Integer read " << valint << endl ;
cout << "Double read " << valdouble << endl ;

// Reading Kadath classes
// Space first, its exact type must be known
Space_spheric space (fin) ;
cout << space << endl ;

// Then the fields
Scalar field (space, fin) ;
Vector vecU (space, fin) ;

// Don't forget to close the file in the end
fclose(fin) ;