Java 2 Ada - Tag files2020-08-09T20:49:00+00:00Stephane Carrezurn:md5:d12e23c53b2436d6becce3d51ddbdf38AWAEasy reading and writing files with Ada Utility Libraryurn:md5:3b8780a649dd29ae069d836ebd6c052e2020-08-09T20:49:00+00:002020-08-09T20:49:00+00:00Stephane CarrezAdaTutorialfiles
<div class="post-text"><p>The <a href="https://github.com/stcarrez/ada-util">Ada Utility Library</a> provides several simple operations that simplify the reading and writing of files through a single procedure call. These operations are not new since I've implemented most of them 10 years ago!!!</p><p>Reading a file line by line by using <code>Ada.Text_IO</code> is quite easy but annoying due to the fact that you have to open the file, iterate over the content getting one line at a time and then closing the file. To simplify this process, the <a href="https://github.com/stcarrez/ada-util/blob/master/src/base/files/util-files.ads">Util.Files</a> package of <a href="https://github.com/stcarrez/ada-util">Ada Utility Library</a> provides a simple <code>Read_File</code> procedure that uses a procedure as parameter and that procedure will be called for each line that is read.</p><pre><code class="lang-ada">with Util.Files;
procedure Read_Line (Line : in String) is ...;
Util.Files.Read_File (Path => "file.txt",
Process => Read_Line'Access);
</code></pre><p>Another <code>Read_File</code> procedure allows to read the file and get its content in a vector of strings so that once the file is read the vector contains each line. Yet, another <code>Read_File</code> procedure reads the file content in an <code>Unbounded_String</code>. You will use that later form as follows:</p><pre><code class="lang-ada">with Util.Files;
with Ada.Strings.Unbounded;
Content : Ada.Strings.Unbounded.Unbounded_String;
Util.Files.Read_File (Path => "file.txt",
Into => Content);
</code></pre><p>Very often it is also necessary to write some content in a file. Again, this is easy to do but a simple <code>Write_File</code> procedure that takes the file path and the content to write is easier to use in several cases:</p><pre><code class="lang-ada">with Util.Files;
Util.Files.Write_File (Path => "file.txt",
Content => "something");
</code></pre><p>The <a href="https://github.com/stcarrez/ada-util">Ada Utility Library</a> contains other useful operations and features that have helped me in implementing various projects such as <a href="https://github.com/stcarrez/ada-awa">Ada Web Application</a> and <a href="https://github.com/stcarrez/ada-keystore">Ada Keystore</a>. Have a look at the <a href="https://ada-util.readthedocs.io/en/latest/">Ada Utility Library Programmer's Guide</a>!</p></div>