From 167c54a2c8df1c94c2bcefb7ed4b40dd0b833802 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jakub=20Klinkovsk=C3=BD?= <klinkovsky@mmg.fjfi.cvut.cz> Date: Wed, 20 Apr 2022 10:34:54 +0200 Subject: [PATCH] Added File::ignore --- src/TNL/File.h | 12 ++++++++++++ src/TNL/File.hpp | 9 +++++++++ src/UnitTests/FileTest.h | 5 ++++- 3 files changed, 25 insertions(+), 1 deletion(-) diff --git a/src/TNL/File.h b/src/TNL/File.h index 92dfd58e4e..7449a15921 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 0d10985f2a..2252028cd4 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 7af5fb286e..dee033c5e1 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 ); -- GitLab