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