From 03eb463f1c072581177009df50152533a4ff7c40 Mon Sep 17 00:00:00 2001 From: LaurentBerger Date: Wed, 28 Mar 2018 14:35:38 +0200 Subject: [PATCH] Solves #11156 (#11160) * Solves #11156 * Check file size for all file format. Disable APPEND if file is empty * Add test for APPEND mode --- modules/core/src/persistence_c.cpp | 8 ++++++-- modules/core/test/test_io.cpp | 18 ++++++++++++++++++ 2 files changed, 24 insertions(+), 2 deletions(-) diff --git a/modules/core/src/persistence_c.cpp b/modules/core/src/persistence_c.cpp index d7542ce291..ed315d0971 100644 --- a/modules/core/src/persistence_c.cpp +++ b/modules/core/src/persistence_c.cpp @@ -206,8 +206,12 @@ cvOpenFileStorage( const char* query, CvMemStorage* dststorage, int flags, const // and factor=4 for YAML ( as we use 4 bytes for non ASCII characters (e.g. \xAB)) int buf_size = CV_FS_MAX_LEN*(fs->fmt == CV_STORAGE_FORMAT_XML ? 6 : 4) + 1024; - if( append ) + if (append) + { fseek( fs->file, 0, SEEK_END ); + if (ftell(fs->file) == 0) + append = false; + } fs->write_stack = cvCreateSeq( 0, sizeof(CvSeq), fs->fmt == CV_STORAGE_FORMAT_XML ? sizeof(CvXMLStackRecord) : sizeof(int), fs->memstorage ); @@ -301,7 +305,7 @@ cvOpenFileStorage( const char* query, CvMemStorage* dststorage, int flags, const } else if( fs->fmt == CV_STORAGE_FORMAT_YAML ) { - if( !append ) + if( !append) icvPuts( fs, "%YAML:1.0\n---\n" ); else icvPuts( fs, "...\n---\n" ); diff --git a/modules/core/test/test_io.cpp b/modules/core/test/test_io.cpp index 9b61667662..6b39c41b3b 100644 --- a/modules/core/test/test_io.cpp +++ b/modules/core/test/test_io.cpp @@ -602,6 +602,24 @@ TEST(Core_InputOutput, FileStorageSpaces) EXPECT_NO_THROW(f2[cv::format("key%d", i)] >> valuesRead[i]); ASSERT_STREQ(values[i].c_str(), valuesRead[i].c_str()); } + std::string fileName = cv::tempfile(".xml"); + cv::FileStorage g1(fileName, cv::FileStorage::WRITE); + for (size_t i = 0; i < 2; i++) { + EXPECT_NO_THROW(g1 << cv::format("key%d", i) << values[i]); + } + g1.release(); + cv::FileStorage g2(fileName, cv::FileStorage::APPEND); + for (size_t i = 2; i < valueCount; i++) { + EXPECT_NO_THROW(g2 << cv::format("key%d", i) << values[i]); + } + g2.release(); + cv::FileStorage g3(fileName, cv::FileStorage::READ); + std::string valuesReadAppend[valueCount]; + for (size_t i = 0; i < valueCount; i++) { + EXPECT_NO_THROW(g3[cv::format("key%d", i)] >> valuesReadAppend[i]); + ASSERT_STREQ(values[i].c_str(), valuesReadAppend[i].c_str()); + } + g3.release(); } struct data_t