Gobelijn API documentation  - generated for commit a0cbea7
 All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
raii/random-read-files/main.cpp
Go to the documentation of this file.
1 /*
2  * This file is part of the gobelijn software.
3  * Gobelijn is free software: you can redistribute it and/or modify it
4  * under the terms of the GNU General Public License as published by the
5  * Free Software Foundation, either version 3 of the License, or any later
6  * version. Gobelijn is distributed in the hope that it will be useful, but
7  * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
8  * or FITNESS FOR A PARTICULAR PURPOSE.
9  * See the GNU General Public License for details. You should have received
10  * a copy of the GNU General Public License along with the software. If not,
11  * see <http://www.gnu.org/licenses/>.
12  *
13  * Copyright 2016, Jan Broeckhove.
14  */
20 #include <iostream>
21 
22 #include "../files/file.h"
23 #include "random-read-file.h"
24 
25 using namespace Raii;
26 
27 // Reads out the given length-prefixed file in reverse.
28 void tacFile(const RandomReadFile& raFile)
29 {
30  // First, read the file's length.
31  auto length = static_cast<int>(raFile[0]);
32 
33  // Then, read out the file's data backwards.
34  for (int i = length; i >= 1; i--)
35  std::cout << raFile[i];
36  std::cout << std::endl;
37 }
38 
39 int main()
40 {
41  // To test that random-read files actually work, we will encode the alphabet
42  // in a file, prefix that by the alphabet's length, and then read it out
43  // backwards.
44 
45  {
46  File file("tmp_file.txt", "w");
47  // First, write the number of characters that we're going to write.
48  // This is the length of the alphabet, and that's actually pretty easy
49  // to compute up-front.
50  file.WriteChar('z' - 'a' + 1);
51 
52  // Write the alphabet to the file (this is based on the assumption
53  // that 'char' is an ASCII character, but that's actually fairly
54  // reasonable for a small example like this)
55  for (char c = 'a'; c <= 'z'; c++)
56  file.WriteChar(c);
57 
58  // 'tmp_file.txt' is closed automatically by the destructor when 'file'
59  // goes out of scope (which is right about now).
60  }
61  {
62  RandomReadFile raFile("tmp_file.txt");
63  tacFile(raFile);
64 
65  // Destructor will take care of things from here.
66  }
67 }
A wrapper around the C FILE*-based IO API.
Definition: file.h:47
RAII random read file class.
A file that supports random reads: reads that are based on an offset.
void WriteChar(char Value)
Writes a single character to the file.
Definition: file.h:114
void tacFile(const RandomReadFile &raFile)