Skip to content

Commit bdf1035

Browse files
committed
Add filesystem helper: read_file_by_lines()
1 parent 71b914a commit bdf1035

2 files changed

Lines changed: 38 additions & 4 deletions

File tree

include/openPMD/auxiliary/Filesystem.hpp

Lines changed: 17 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -100,5 +100,20 @@ std::string
100100
collective_file_read( std::string const & path, MPI_Comm );
101101

102102
#endif
103-
} // namespace auxiliary
104-
} // namespace openPMD
103+
104+
struct no_such_file_error
105+
{
106+
};
107+
108+
/**
109+
* @brief Read a file line by line.
110+
*
111+
* @param path Path to the file.
112+
* @return Lines of the read file, excluding newline characters.
113+
*
114+
* @throws no_such_file_error
115+
*/
116+
std::vector< std::string >
117+
read_file_by_lines( std::string const & path );
118+
} // auxiliary
119+
} // openPMD

src/auxiliary/Filesystem.cpp

Lines changed: 21 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,6 +35,8 @@
3535
#include <iostream>
3636
#include <stdexcept>
3737
#include <system_error>
38+
#include <fstream>
39+
#include <sstream>
3840

3941

4042
namespace openPMD
@@ -258,5 +260,22 @@ collective_file_read( std::string const & path, MPI_Comm comm )
258260

259261
#endif
260262

261-
} // namespace auxiliary
262-
} // namespace openPMD
263+
std::vector< std::string >
264+
read_file_by_lines( std::string const & path )
265+
{
266+
std::vector< std::string > res;
267+
std::ifstream file( path, std::ios_base::in );
268+
if ( file.fail( ) )
269+
{
270+
throw no_such_file_error( );
271+
}
272+
std::string line;
273+
while( std::getline( file, line ) )
274+
{
275+
res.push_back( std::move( line ) );
276+
line = std::string( );
277+
}
278+
return res;
279+
}
280+
} // auxiliary
281+
} // openPMD

0 commit comments

Comments
 (0)