ALib C++ Framework
by
Library Version: 2605 R0
Documentation generated by doxygen
Loading...
Searching...
No Matches
textfile.hpp
Go to the documentation of this file.
1//==================================================================================================
2/// \file
3/// This header-file is part of the \aliblong.
4///
5/// Copyright 2013-2026 A-Worx GmbH, Germany.
6/// Published under #"mainpage_license".
7//==================================================================================================
8ALIB_EXPORT namespace alib { namespace system {
9
10/// A rather simple text file line-reader. While this is used with the class #"TTextFile",
11/// it might well be used as a standalone helper, i.e. in cases where the text file is
12/// read but does not need to be stored in a vector.
13/// @tparam TLocalBufferSize The size of the local buffer. If lines are wider and the local
14/// buffer is exceeded, it will be replaced by an heap-allocated
15/// buffer, which is then reused for any further line.<br>
16/// Defaults to 1024.
17template <size_t TLocalBufferSize= 1024>
19 std::ifstream IFStream; ///< The input stream opened on construction.
20 NLocalString<TLocalBufferSize> Line; ///< The line buffer.
21 IStreamLineN ReadOp; ///< An <em>AString-appendable</em> object
22 ///< used for reading.
23 std::errc Status; ///< Set after construction. If value is \c 0,
24 ///< the file was correctly opened.
25
26 protected:
27 /// Implementation of the two constructors.
28 /// @param filePath The path of the text-file to read.
29 void construct( const CPathString& filePath ) {
30 Line.DbgDisableBufferReplacementWarning();
31 errno= 0;
32 Path tFilePath(filePath);
33 ALIB_STRINGS_TO_NARROW(filePath, nFilePath, 256)
34 IFStream.open( nFilePath );
35 Status= std::errc(errno);
36 if ( !IFStream.is_open() ) {
37 ALIB_WARNING( "FILETREE/TEXTFILE", "Error <{}: \"{}\"> opening input file \"{}\"",
38 errno, std::errc(errno), filePath)
39 return;
40 }
41 ALIB_MESSAGE( "FILETREE/TEXTFILE", "file \"{}\" opened for reading", filePath)
42 }
43 public:
44
45 /// Constructor. Opens the file specified by \p{filePath}.
46 /// On success, the field #"Status" will hold std::errc(0), an error code otherwise.
47 /// @param filePath The path of the text-file to read.
50 , Status{0} { construct(filePath); }
51
52 /// Reads the next text-line into the field #".Line" and returns a #"%^Substring" pointing to it.
53 /// When the end of the file is reached, the returned object is \e nulled.\b
54 /// Prior to the invocation, method #"TIStreamLine;IsEOF" may be called to detect the end of
55 /// the file actively.
56 /// @return The next line read, or #"NULL_STRING" when all lines were read.
58 Line.Reset( ReadOp );
59 if (ReadOp.IsEOF && Line.IsEmpty())
60 return NULL_NSTRING;
61 return Line;
62 }
63};
64
65
66/// Deduction guide fixing the template parameter #\p{TLocalBufferSize} to its default \c 1024.
68
69#if !DOXYGEN
70# if ALIB_MONOMEM
71# define TEXTFILE_DEFAULT_ALLOCATOR MonoAllocator
72# else
73# define TEXTFILE_DEFAULT_ALLOCATOR HeapAllocator
74# endif
75#endif
76
77
78/// A rather simple text file reader and writer.
79/// @see Reading is performed using the helper type #"TextFileLineReader",
80/// which can be used as a standalone helper, i.e. in cases where a text file is
81/// read but does not need to be stored in a vector.
82/// @tparam TNString The string-type.
83/// This may also be a type derived from #"NString;2"
84/// which contains further fields available with each line of the file.
85/// @tparam TAllocator The #"lang::Allocator;allocator type" to use. In the presence of
86/// module \alib_monomem, this defaults to #"MonoAllocator", and to
87/// #"HeapAllocator" otherwise.
88/// @tparam TLocalBufferSize The size of the local buffer. If lines are wider and the local
89/// buffer is exceeded, it will be replaced by an heap-allocated
90/// buffer, which is then reused for any further line.<br>
91/// Defaults to 1024.
92template <typename TNString= NString, typename TAllocator= TEXTFILE_DEFAULT_ALLOCATOR,
93 size_t TLocalBufferSize= 1024>
94class TTextFile : public lang::AllocatorMember<TAllocator>
95 , public std::vector<TNString, lang::StdAllocator<TNString, TEXTFILE_DEFAULT_ALLOCATOR>> { // StdVectorMA<TNString>
96 protected:
97 /// The allocator member base-type.
99 public:
100 /// Type definition publishing template parameter \p{TAllocator}.
101 using AllocatorType = TAllocator;
102
103 /// Type definition publishing the type in the <c>std::vector</c> that this type is derived
104 /// of.
105 /// (As is defined with template parameter \p{TNString}.)
106 using StoredType = TNString;
107
108 /// Type definition publishing the base container type.
109 using Vector= std::vector<TNString, lang::StdAllocator<TNString, TEXTFILE_DEFAULT_ALLOCATOR>>;
110
111 /// Constructor.
112 /// @param ma The allocator to use.
114 : lang::AllocatorMember<TAllocator>(ma)
115 , Vector(ma) {}
116
117 /// Returns the vector's size as \alib's signed integral type.
118 /// @return The number of lines in this source file.
119 constexpr integer Size() const noexcept { return int(Vector::size()); }
120
121 /// Returns the element in the vector at the given position.<br>
122 /// Note that this is the same as calling inherited <c>std::vector::at()</c>, but this method
123 /// accepts any integral type for parameter \p{idx}.<br>
124 /// Furthermore, this method raises an \alib_assertion in debug-builds, instead of throwing
125 /// an exception.
126 /// @tparam TIntegral The integral type that the index is provided by.
127 /// @param idx The index to retrieve an element for.
128 /// @return A reference to the element stored at the given \p{idx}.
129 template<typename TIntegral>
130 [[nodiscard]]
131 constexpr StoredType& At(TIntegral idx) noexcept { return Vector::at(size_t(idx)); }
132
133 /// <c>const</c>-version of #"At".
134 /// @tparam TIntegral The integral type that the index is provided by.
135 /// @param idx The index to retrieve an element for.
136 /// @return A \c const reference to the element stored at the given \p{idx}.
137 template<typename TIntegral>
138 [[nodiscard]]
139 constexpr const StoredType& At(TIntegral idx) const noexcept { return Vector::at(size_t(idx)); }
140
141 /// Reads the file into this vector of lines.
142 /// @param filePath The path of the file.
143 /// @return <c>std::errc(0)</c> if all went well, otherwise an error code.
144 std::errc Read(const CPathString& filePath) {
146 if ( reader.Status != std::errc(0) )
147 return reader.Status;
148
149 NSubstring line;
150 while ( (line= reader.NextLine()).IsNotNull() ) {
151 if constexpr (std::is_same_v<StoredType, TNString>)
152 Vector::emplace_back( base::GetAllocator(), line );
153 else {
155 lineStr._(line);
156 Vector::emplace_back( base::GetAllocator(), lineStr );
157 } }
158
159 ALIB_MESSAGE( "FILETREE/TEXTFILE", "File \"{}\", {} lines read", filePath, Vector::size() )
160
161 return std::errc(0);
162 }
163
164 /// Writes this text file to the given \p{filePath}.
165 /// @param filePath The path of the file.
166 /// @return <c>std::errc(0)</c> if all went well, otherwise an error code.
168 std::errc Write(const PathString& filePath) {
169 errno= 0;
170 Path tFilePath(filePath);
171 ALIB_STRINGS_TO_NARROW(tFilePath, nTFilePath, 256)
172 std::ofstream oFile( nTFilePath.Terminate() );
173 if ( !oFile.is_open() ) {
174 auto result= std::errc(errno);
175 ALIB_WARNING( "FILETREE/TEXTFILE", "Error <{}: \"{}\"> opening output file \"{}\"",
176 errno, result, filePath)
177 return result;
178 }
179 ALIB_MESSAGE( "FILETREE/TEXTFILE", "file \"{}\" opened for writing", filePath)
180
181 for( auto& line : *this )
182 oFile << line << std::endl;
183
184 ALIB_MESSAGE( "FILETREE/TEXTFILE", "File \"{}\", {} lines written", filePath, Vector::size() )
185
186 return std::errc(0);
187 }
188
189};
190
191} // namespace alib[::system]
192
193/// Type alias in namespace #"%alib".
194/// @tparam TLocalBufferSize The size of the local buffer. If lines are wider and the local
195/// buffer is exceeded, it will be replaced by a heap-allocated
196/// buffer, which is then reused for any further line.<br>
197/// Defaults to 1024.
198template <size_t TLocalBufferSize= 1024>
200
201/// Type alias in namespace #"%alib".
202/// @tparam TLocalBufferSize The size of the local buffer. If lines are wider and the local
203/// buffer is exceeded, it will be replaced by a heap-allocated
204/// buffer, which is then reused for any further line.<br>
205/// Defaults to 1024.
206template <size_t TLocalBufferSize= 1024>
208
209#if !DOXYGEN
210# undef TEXTFILE_DEFAULT_ALLOCATOR
211#endif
212
213
214} // namespace [alib]
#define ALIB_MESSAGE(domain,...)
#define ALIB_DLL
#define ALIB_WARNING(domain,...)
#define ALIB_EXPORT
TAString & _(const TAppendable &src)
constexpr integer Size() const noexcept
Definition textfile.hpp:119
std::errc Write(const PathString &filePath)
Definition textfile.hpp:168
constexpr StoredType & At(TIntegral idx) noexcept
Definition textfile.hpp:131
TTextFile(AllocatorType &ma)
Definition textfile.hpp:113
constexpr const StoredType & At(TIntegral idx) const noexcept
Definition textfile.hpp:139
std::vector< TNString, lang::StdAllocator< TNString, TEXTFILE_DEFAULT_ALLOCATOR > > Vector
Type definition publishing the base container type.
Definition textfile.hpp:109
TAllocator AllocatorType
Type definition publishing template parameter TAllocator.
Definition textfile.hpp:101
lang::AllocatorMember< TAllocator > base
The allocator member base-type.
Definition textfile.hpp:98
std::errc Read(const CPathString &filePath)
Definition textfile.hpp:144
Definition alox.cpp:14
strings::TString< nchar > NString
Type alias in namespace #"%alib".
Definition string.hpp:2174
system::TextFileLineReader< TLocalBufferSize > TextFileLineReader
Definition textfile.hpp:199
constexpr NString NULL_NSTRING
A nulled string of the narrow character type.
Definition string.hpp:2256
lang::integer integer
Type alias in namespace #"%alib".
Definition integers.hpp:149
system::TTextFile< NString, TEXTFILE_DEFAULT_ALLOCATOR, TLocalBufferSize > TextFile
Definition textfile.hpp:207
strings::TLocalString< nchar, TCapacity, lang::HeapAllocator > NLocalString
Type alias in namespace #"%alib".
strings::TCString< PathCharType > CPathString
The string-type used with this ALib Module.
Definition path.hpp:37
strings::TString< PathCharType > PathString
The string-type used with this ALib Module.
Definition path.hpp:34
strings::TSubstring< nchar > NSubstring
Type alias in namespace #"%alib".
strings::compatibility::std::TIStreamLine< alib::nchar > IStreamLineN
Type alias in namespace #"%alib".
#define ALIB_STRINGS_TO_NARROW( src, dest, bufSize)
TEXTFILE_DEFAULT_ALLOCATOR & GetAllocator() const noexcept
TextFileLineReader(const CPathString &filePath)
Definition textfile.hpp:48
void construct(const CPathString &filePath)
Definition textfile.hpp:29