Gobelijn API documentation  - generated for commit a0cbea7
 All Classes Namespaces Files Functions Variables Typedefs Friends Macros Pages
raii/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 <cstdio>
21 #include <iostream>
22 
23 #include "file.h"
24 
25 using namespace Raii;
26 
30 void printFile(File& file)
31 {
32  int c;
33  while ((c = file.ReadChar()) != EOF)
34  std::cout << static_cast<char>(c);
35  std::cout << std::endl;
36 }
37 
38 int main()
39 {
40  {
41  // Open 'tmp_file.txt' in write-mode by invoking the constructor.
42  File file("tmp_file.txt", "w");
43 
44  // Write the alphabet to the file (this is based on the assumption
45  // that 'char' is an ASCII character, but that's actually fairly
46  // reasonable for a small example like this)
47  for (char c = 'a'; c <= 'z'; c++)
48  file.WriteChar(c);
49 
50  // 'tmp_file.txt' is closed automatically by the destructor when 'file'
51  // goes out of scope (which is right about now).
52  }
53  {
54  // Open 'tmp_file.txt' again by invoking the constructor, but this
55  // time, we'll open it in read-mode.
56  File file("tmp_file.txt", "r");
57 
58  // Dump the file's contents to stdout.
59  printFile(file);
60 
61  // We can also close the file manually. The destructor will do nothing
62  // in that case.
63  file.Close();
64  }
65 }
int main()
RAII File class.
A wrapper around the C FILE*-based IO API.
Definition: file.h:47
void printFile(File &file)
Prints the contents of the given file.
int ReadChar()
Reads the next input character from this file.
Definition: file.h:101
void WriteChar(char Value)
Writes a single character to the file.
Definition: file.h:114
void Close()
Closes this file resource.
Definition: file.h:89