LHAPDF  6.5.5
All Classes Namespaces Files Functions Variables Typedefs Enumerations Modules Pages
FileIO.h
1 // -*- C++ -*-
2 //
3 // This file is part of LHAPDF
4 // Copyright (C) 2012-2024 The LHAPDF collaboration (see AUTHORS for details)
5 //
6 #pragma once
7 #ifndef LHAPDF_FileIO_H
8 #define LHAPDF_FileIO_H
9 
10 // STL includes
11 #include <fstream>
12 #include <sstream>
13 #include <string>
14 
15 /// Namespace for all LHAPDF functions and classes
16 namespace LHAPDF {
17 
18 
19  /// @brief MPI-safe file I/O interface
20  template <class FILETYPE>
21  class File {
22  public:
23 
24  // Constructor
25  File(const std::string& name)
26  : _name(name), _fileptr(nullptr), _streamptr(nullptr) {
27  open();
28  }
29 
30  /// Destructor
31  ~File() { close(); }
32 
33 
34  /// Open file
35  bool open();
36 
37  /// Close file
38  bool close();
39 
40  /// Forward methods via pointer emulation
41  FILETYPE* operator->() const { return _fileptr; }
42 
43  /// Forward methods via pointer-dereference emulation
44  FILETYPE& operator*() const { return *_fileptr; }
45 
46  /// Get the file content
47  std::string getContent() const { return _streamptr != nullptr ? _streamptr->str() : ""; }
48 
49 
50  protected:
51 
52  std::string _name;
53 
54  FILETYPE* _fileptr;
55 
56  std::stringstream* _streamptr;
57 
58  };
59 
60 
61  // Convenience aliases (NB. have to use #defines due to how .cc template building works)
62  // typedef File<std::ifstream> IFile;
63  // typedef File<std::ofstream> OFile;
64  #define IFile File<std::ifstream>
65  #define OFile File<std::ofstream>
66 
67 
68  /// Global function to flush the MPI-safe file cache
70 
71 
72 }
73 #endif