ALib C++ Library
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 \ref mainpage_license "Boost Software 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 class \alib{files;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.
25 std::ifstream IFStream; ///< The input stream opened on construction.
26 NString4K Line; ///< The line buffer.
27 alib::IStreamLine ReadOp; ///< An <em>AString-appendable</em> object used for reading.
28 system::SystemErrors Status; ///< Set after construction. If \b SystemErrors::OK, the file
29 ///< was correctly opened.
30
31 protected:
32 /// Implementation of the two constructors.
33 /// @param filePath The path of the text-file to read.
34 void construct( const CString& filePath ) {
35 errno= 0;
36 Path tFilePath(filePath);
37 ALIB_STRINGS_TO_NARROW(filePath, nFilePath, 256)
38 IFStream.open( nFilePath );
39 if ( !IFStream.is_open() ) {
40 ALIB_WARNING( "FILES/TEXTFILE", "Error <{}: \"{}\"> opening input file \"{}\"",
41 errno, system::SystemErrors(errno), filePath)
42 return;
43 }
44 ALIB_MESSAGE( "FILES/TEXTFILE", "file \"{}\" opened for reading", filePath)
45 }
46 public:
47
48 /// Constructor. Opens the file specified by \p{filePath}.
49 /// On success, the field #Status will hold \alib{system;SystemErrors;SystemErrors::OK},
50 /// an error code otherwise.
51 /// @param filePath The path of the text-file to read.
52 TextFileLineReader( const CString& filePath )
54 , Status{SystemErrors::OK} { construct(filePath); }
55
56 /// Alternative constructor taking a \alib{files;File} object instead of a file's path string.
57 /// @param file The text-file to read.
60 , Status{SystemErrors::OK} {
61 Path filePath;
62 file.AsCursor().AssemblePath(filePath);
63 construct(filePath);
64 }
65
66 /// Reads the next text-line into the field #Line and returns a \b Substring pointing to it.
67 /// When the end of the file is reached, the returned object is \e nulled.\b
68 /// Prior to the invocation, method \alib{strings::compatibility::std::TIStreamLine;IsEOF}
69 /// may be called to detect the end of the file actively.
70 /// @return The next line read, or \alib{NULL_STRING} when all lines were read.
72 Line.Reset( ReadOp );
73 if (ReadOp.IsEOF && Line.IsEmpty())
74 return NULL_STRING;
75 return Line;
76 }
77};
78
79/// A rather simple text file reader and writer.
80/// @see Reading is performed using helper type class \alib{files;TextFileLineReader},
81/// which be used as a standalone helper, i.e. in cases where a text file is
82/// read but does not need to be stored in a vector.
83/// @tparam TNString The string-type.
84/// This may also be a type derived from \alib{NString}
85/// which contains further fields available with each line of the file.
86/// @tparam TAllocator The \alib{lang;Allocator;allocator type} to use.
87template <typename TNString= NString, typename TAllocator= MonoAllocator>
88class TTextFile : public lang::AllocatorMember<TAllocator>
89 , public StdVectorMA<TNString>
90{
91 protected:
92 /// The given allocator
94
95 public:
96 /// Type definition publishing template parameter \p{TAllocator}.
97 using AllocatorType = TAllocator;
98
99 /// Type definition publishing the type in the <c>std::vector</c> that this type is derived
100 /// of.
101 /// (As is defined with template parameter \p{TNString}.)
102 using StoredType = TNString;
103
104 /// Type definition publishing the base container type.
106
107 /// Constructor.
108 /// @param ma The allocator to use.
110 : lang::AllocatorMember<TAllocator>(ma)
111 , Vector(ma)
112 , allocator( ma ) {}
113
114 /// Returns the vector's size as \alib's signed integral type.
115 /// @return The number of lines in this source file.
116 constexpr integer Size() const noexcept { return int(Vector::size()); }
117
118 /// Returns the element in the vector at the given position.<br>
119 /// Note that this is the same as calling inherited <c>std::vector::at()</c>, but this method
120 /// accepts any integral type for parameter \p{idx}.<br>
121 /// Furthermore, this method raises an \alib_assertion in debug-builds, instead of throwing
122 /// an exception.
123 /// @tparam TIntegral The integral type that the index is provided by.
124 /// @param idx The index to retrieve an element for.
125 /// @return A reference to the element stored at the given \p{idx}.
126 template<typename TIntegral>
127 [[__nodiscard__]]
128 constexpr StoredType& At(TIntegral idx) noexcept { return Vector::at(size_t(idx)); }
129
130 /// <c>const</c>-version of #At.
131 /// @tparam TIntegral The integral type that the index is provided by.
132 /// @param idx The index to retrieve an element for.
133 /// @return A \c const reference to the element stored at the given \p{idx}.
134 template<typename TIntegral>
135 [[__nodiscard__]]
136 constexpr const StoredType& At(TIntegral idx) const noexcept { return Vector::at(size_t(idx)); }
137
138 /// Reads the file into this vector of lines.
139 /// @param filePath The path of the file.
140 /// @return \alib{system;SystemErrors;SystemErrors::OK} if all went well, otherwise an
141 /// error code.
143 TextFileLineReader reader(filePath);
144 if ( reader.Status != system::SystemErrors::OK )
145 return reader.Status;
146
147 Substring line;
148 while ( (line= reader.NextLine()).IsNotNull() )
149 Vector::emplace_back( allocator, line );
150
151 ALIB_MESSAGE( "FILES/TEXTFILE", "File \"{}\", {} lines read", filePath, Vector::size() )
152
153 return system::SystemErrors::OK;
154 }
155
156 /// Reads the file into this vector of lines.
157 /// @param file The file to read.
158 /// @return \alib{system;SystemErrors;SystemErrors::OK} if all went well, otherwise an
159 /// error code.
161 Path filePath;
162 file.AsCursor().AssemblePath(filePath);
163 return Read(filePath);
164 }
165
166 /// Writes this text file to the given \p{filePath}.
167 /// @param filePath The path of the file.
168 /// @return \alib{system;SystemErrors;SystemErrors::OK} if all went well, otherwise an
169 /// error code.
172 errno= 0;
173 Path tFilePath(filePath);
174 ALIB_STRINGS_TO_NARROW(tFilePath, nTFilePath, 256)
175 std::ofstream oFile( nTFilePath.Terminate() );
176 if ( !oFile.is_open() ) {
177 auto result= system::SystemErrors(errno);
178 ALIB_WARNING( "FILES/TEXTFILE", "Error <{}: \"{}\"> opening output file \"{}\"",
179 errno, result, filePath)
180 return result;
181 }
182 ALIB_MESSAGE( "FILES/TEXTFILE", "file \"{}\" opened for writing", filePath)
183
184 for( auto& line : *this )
185 oFile << line << std::endl;
186
187 ALIB_MESSAGE( "FILES/TEXTFILE", "File \"{}\", {} lines written", filePath, Vector::size() )
188
189 return system::SystemErrors::OK;
190 }
191
192};
193
194} // namespace alib[::files]
195
196/// Type alias in namespace \b alib.
198
199/// Type alias in namespace \b alib.
201
202
203} // namespace [alib]
204
205#endif // ALIB_FILES
206
207#endif // H_ALIB_FILES_TEXTFILE
Cursor & AsCursor()
Definition ftree.inl:711
constexpr const StoredType & At(TIntegral idx) const noexcept
TTextFile(MonoAllocator &ma)
TAllocator AllocatorType
Type definition publishing template parameter TAllocator.
StdVectorMA< TNString > Vector
Type definition publishing the base container type.
system::SystemErrors Read(const CString &filePath)
constexpr StoredType & At(TIntegral idx) noexcept
ALIB_DLL system::SystemErrors Write(const String &filePath)
system::SystemErrors Read(files::File file)
constexpr integer Size() const noexcept
#define ALIB_MESSAGE(domain,...)
Definition alib.inl:1064
#define ALIB_DLL
Definition alib.inl:503
#define ALIB_STRINGS_TO_NARROW( src, dest, bufSize)
#define ALIB_WARNING(domain,...)
Definition alib.inl:1063
constexpr String NULL_STRING
A nulled string of the default character type.
Definition string.inl:2271
files::TextFileLineReader TextFileLineReader
Type alias in namespace alib.
std::vector< T, StdMA< T > > StdVectorMA
Type alias in namespace alib.
strings::TCString< character > CString
Type alias in namespace alib.
Definition cstring.inl:475
lang::integer integer
Type alias in namespace alib.
Definition integers.inl:149
monomem::TMonoAllocator< lang::HeapAllocator > MonoAllocator
system::Path Path
Type alias in namespace alib.
Definition path.inl:376
strings::compatibility::std::TIStreamLine< alib::character > IStreamLine
Type alias in namespace alib.
strings::TString< character > String
Type alias in namespace alib.
Definition string.inl:2189
NLocalString< 4096 > NString4K
Type alias name for TLocalString<nchar,8192>.
system::SystemErrors SystemErrors
Type alias in namespace alib.
files::TTextFile< NString > TextFile
Type alias in namespace alib.
strings::TSubstring< character > Substring
Type alias in namespace alib.
NString4K Line
The line buffer.
std::ifstream IFStream
The input stream opened on construction.
alib::IStreamLine ReadOp
An AString-appendable object used for reading.
TextFileLineReader(const CString &filePath)
void construct(const CString &filePath)