Working with files

Note

The functions presented in this chapter mainly deal with objects of type hdf5::file::File. For a full list of operations provided by this type consult the h5cpp manual.

Creating single files

In order to create a file libpniio provides some simple wrappers around the hdf5::file::create() functions provided by h5cpp. These wrappers basically add all the attributes to the root group of an HDF5 file required by the NeXus standard. In order to create a single file use the nexus::create_file() wrapper function which in turn will return an instance of hdf5::file::File

#include <pni/io/nexus.hpp>
#include <h5cpp/hdf5.hpp>

using namespace pni::io;

int main(int argc,char **argv)
{
    hdf5::file::File file = nexus::create_file("test.nxs");
    //... code omitted ...
    file.close();

    return 0;
}

The code should be rather self explaining. If the file already exists a std::runtime_error exception is thrown. In order to overwrite an existing file one can use

h5::file::File file = nexus::create_file("test.nxs",hdf5::file::AccessFlags::TRUNCATE);

This option should be used with case as all data stored in the original file will be lost forever. For more options to create_file() check the API documentation and the h5cpp documentation.

Create distributed files

Todo

Do we really need this feature. Need to discuss this during the next group meeting

Opening and closing files

Like for creating files there is a wrapper function nexus::open_file() to open a NeXus file.

hdf5::file::File f = nexus::open_file("test.nxs");

By default files are opened in read-only mode in order to avoid accidental data manipulations. To open a file for reading and writing use

hdf5::file::File f = nexus::open_file("test.nxs",hdf5::file::AccessFlags::READWRITE);

The object returned by nexus::open_file() is again an instance of hdf5::file::File(). The nexus::open_file() does not check whether or not is a valid NeXus file. In order to perform that check use the is_nexus_file()

boost::filesystem::path file_path = ...;

if(!nexus::is_nexus_file(file_path))
{
   std::cerr<<"File "<<file_path<<" is not a valid NeXus file!"<<std::endl;
   return 1;
}

hdf5::file::File file = nexus::open_file(file_path);