diff --git a/src/TNL/File.h b/src/TNL/File.h index 92dfd58e4edaa89b63a368e4989b48f62997e37b..7449a15921f88774bdf350f8e28518cbfe8a7675 100644 --- a/src/TNL/File.h +++ b/src/TNL/File.h @@ -140,6 +140,18 @@ public: void save( const Type* buffer, std::streamsize elements = 1 ); + /** + * \brief Extracts and discards characters from the file. + * + * Throws \ref std::ios_base::failure on failure. + * + * \tparam SourceType type of data stored on the file, + * \param elements number of elements to be read and ignored. + */ + template< typename SourceType > + void + ignore( std::streamsize elements = 1 ); + protected: // implementation for all allocators which allocate data accessible from host template< typename Type, diff --git a/src/TNL/File.hpp b/src/TNL/File.hpp index 0d10985f2a8ef7803be919d6f79c7b20bd40c179..2252028cd46459c5a753a54c95cd7e7dd31e1da9 100644 --- a/src/TNL/File.hpp +++ b/src/TNL/File.hpp @@ -234,6 +234,15 @@ File::save_impl( const Type* buffer, std::streamsize elements ) #endif } +template< typename SourceType > +void +File::ignore( std::streamsize elements ) +{ + // use seekg instead of ignore for efficiency + // https://stackoverflow.com/a/31246560 + file.seekg( sizeof( SourceType ) * elements, std::ios_base::cur ); +} + inline bool fileExists( const String& fileName ) { diff --git a/src/UnitTests/FileTest.h b/src/UnitTests/FileTest.h index 7af5fb286ee1f831b2db5c98d0acd119c5ec60ab..dee033c5e1549b42922407ef181f13781dc9e735 100644 --- a/src/UnitTests/FileTest.h +++ b/src/UnitTests/FileTest.h @@ -18,11 +18,13 @@ TEST( FileTest, WriteAndRead ) File file; ASSERT_NO_THROW( file.open( String( TEST_FILE_NAME ), std::ios_base::out ) ); - int intData( 5 ); + int intData = 5; double doubleData[ 3 ] = { 1.0, 2.0, 3.0 }; + const int ignoredValue = 42; const double constDoubleData = 3.14; ASSERT_NO_THROW( file.save( &intData ) ); ASSERT_NO_THROW( file.save( doubleData, 3 ) ); + ASSERT_NO_THROW( file.save( &ignoredValue ) ); ASSERT_NO_THROW( file.save( &constDoubleData ) ); ASSERT_NO_THROW( file.close() ); @@ -32,6 +34,7 @@ TEST( FileTest, WriteAndRead ) double newConstDoubleData; ASSERT_NO_THROW( file.load( &newIntData, 1 ) ); ASSERT_NO_THROW( file.load( newDoubleData, 3 ) ); + ASSERT_NO_THROW( file.ignore< decltype(ignoredValue) >( 1 ) ); ASSERT_NO_THROW( file.load( &newConstDoubleData, 1 ) ); EXPECT_EQ( newIntData, intData );