Error readStringFromFile( const core::FilePath& filePath, const Filter& filter, std::string* pContents, string_utils::LineEnding lineEnding=string_utils::LineEndingPassthrough) { try { // open the file stream (report errors with exceptions) boost::shared_ptr<std::istream> pIfs; Error error = filePath.open_r(&pIfs); if (error) return error; pIfs->exceptions(std::istream::failbit | std::istream::badbit); // output string stream (report errors with exceptions) std::stringstream ostr; ostr.exceptions(std::ostream::failbit | std::ostream::badbit); // do the copy boost::iostreams::filtering_ostream filteringOStream ; filteringOStream.push(filter); filteringOStream.push(ostr); boost::iostreams::copy(*pIfs, filteringOStream, 128); // return contents with requested line endings *pContents = ostr.str(); string_utils::convertLineEndings(pContents, lineEnding); return Success(); } catch(const std::exception& e) { Error error = systemError(boost::system::errc::io_error, ERROR_LOCATION); error.addProperty("what", e.what()); error.addProperty("path", filePath.absolutePath()); return error; } return Success(); }
Error readCollectionFromFile( const core::FilePath& filePath, CollectionType* pCollection, boost::function<ReadCollectionAction(const std::string& line, typename CollectionType::value_type* pValue)> parseFunction, bool trimAndIgnoreBlankLines=true) { using namespace boost::system::errc ; // open the file stream boost::shared_ptr<std::istream> pIfs; Error error = filePath.open_r(&pIfs); if (error) return error; // create insert iterator std::insert_iterator<CollectionType> insertIterator(*pCollection, pCollection->begin()); try { // read each line std::string nextLine ; while (true) { // read the next line std::getline(*pIfs, nextLine) ; if (pIfs->eof()) break; else if (pIfs->fail()) return systemError(io_error, ERROR_LOCATION); // trim whitespace then ignore it if it is a blank line if (trimAndIgnoreBlankLines) { boost::algorithm::trim(nextLine) ; if (nextLine.empty()) continue ; } // parse it and add it to the collection typename CollectionType::value_type value ; ReadCollectionAction action = parseFunction(nextLine, &value); if (action == ReadCollectionAddLine) { *insertIterator++ = value ; } else if (action == ReadCollectionIgnoreLine) { // do nothing } else if (action == ReadCollectionTerminate) { break; // exit read loop } } } catch(const std::exception& e) { Error error = systemError(boost::system::errc::io_error, ERROR_LOCATION); error.addProperty("what", e.what()); error.addProperty("path", filePath.absolutePath()); return error; } return Success() ; }