Part 9: File handling
Tags: cpp, beginners, programming
Published: 2021-12-17 10:36:00

Hey guys, welcome to the 9th and final part of my series, C++: Explain like I’m five. We have already covered all necessary concepts to get started programming in C++. Therefore, now we will discuss file handling as it is a relatively important and useful skill to have while programming.

In C++, files are interpreted as a sequence of bytes stored on any storage media.
The data of any file is stored in either readable form or in binary code that is called a text file or a binary file. This is achieved through a header file called "fstream". This library manages two aspects that are interface and the transfer of data. It has a predefined set of operations for file handling through certain classes.


The library has predefined a set of operations for all file handling-related actions through some certain classes.


## **The general file handling steps**

1. Declaring a file name variable
2. Associate the file name variable with the disk file name
3. Open the file
4. Use the file
5. Close the file

## **Streams**

Streams act as an interface between the files and the programs. It indicates the flow of data from a particular device to the program’s variables. The device here refers to files, keyboards, arrays, etc.  These streams are treated as objects to support a consistent access interface. Streams represent a sequence of bytes and then deal with the flow of data.

Each stream is associated with a class. Those classes have functions and operations for a certain kind of data flow.

•	File -> Program (Input stream) - reads

•	Program -> File (Output stream) – write

**Diagramatically speaking:**
![image.png](https://cdn.hashnode.com/res/hashnode/image/upload/v1630173716390/Cw9k8w39O.png)

A stream is basically a series of bytes. It acts either as a source from where data can be extracted or as a destination to where the output can be sent. Streams resemble the producer and consumer models a lot.
The producer produces the items that have to be consumed by the consumer. 
Here, the producer and the consumers are connected by operators: ">>" or "<<".

## **Pre-defined console streams**

C++ has various predefined streams that are opened automatically when the execution of a program starts. 
1. cin : standard input (usually keyboard) corresponding to stdio header file in C
2. cout: standard output (usually screen) corresponding to stdout header file in C 
3. cerr: standard error output (usually screen) corresponding to stderr in C
4. clog: A fully buffered version of cerr (No C equivalent)


## **Some necessary definitions**

**interactive (iostream)**

1. **cin:** input stream associated with keyboard.
2. **cout:** output stream associated with display.

**file (fstream)**

1. **ifstream:** defines new input stream (normally associated with a file).
2. **ofstream:** defines new output stream (normally associated with a file).

## **Why use files?**

• They are a convenient way to deal with large quantities of data.

• They store data permanently or atleast until the file is deleted.

• With help of files, you can avoid typing data into program multiple times.

• You can also share data between programs. 

## **Some necessary things to know before using files**

• How to "connect" a file to a program.

• How to ask the program to read the data.

• How to ask the program to write data.

• How to handle and check errors and EOF.

## **Classes for stream I/O in C++**

• ios (input/output stream) is the base class.

• istream and ostream inherit from ios

• ifstream inherits from istream and ios.

• ofstream inherits from ostream and ios.

• iostream inherits from istream and ostream and ios.

• fstream inherits from ifstream, iostream, and ofstream 

In C++, following can be used:

• **ofstream:** to write data to a file

• **ifstream:** to read data from a file

• **fstream:** for both reading and writing 

## **File Modes**

There are various operations you can perform on the file and that are:

• **ios::in** - Open file to read

• **ios::out** - Open file to write

• **ios::app** - All the date you write, is put at the end of the file. It calls ios::out

• **ios::ate** - All the date you write, is put at the end of the file. It does not call ios::out

• **ios::trunc** - Deletes all previous content in the file. (empties the file)

• **ios::nocreate** - If the file does not exist, opening it with the open() function gets impossible.

• **ios::noreplace** - If the file exists, trying to open it with the open() function, returns an error.

• **ios::binary** - Opens the file in binary mode.

## **File Pointers**

Both the istream and ostream provide some member functions for repositioning the file-position pointer. The members functions for doing so are seekg ("seek get") for istream and seekp ("seek put") for ostream. The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. 

**Example:**

```
infile.seekg(20);
``` 
This action moves the file pointer to the byte number 20. The bytes in a file are numbered starting from zero. Thus, the pointer will be pointing to the 21st byte in the file.

## **Opening the file**

```
#include <fstream>
int main(void)
{
	ofstream outFile("file1.txt", ios::out);
	outFile << "That's new!\n";
	outFile.close();
        return 0;
}

``` 
If you want to set more than one open mode, just use the **OR** operator "|" in this way:
                      
```
 ios::ate | ios::binary
``` 

## **How to deal with Binary files?**

The functions used for binary file handling are:

• **get():** read a byte and point to the next byte to read

• **put():** write a byte and point to the next location to write

• **read():** block reading

• **write():** block writing 

• **flush(): **Save data from the buffer to the output file

**Example:**

```
#include <iostream>
#include <fstream>
void main()
{
	fstream File("test_file",ios::out | ios::in | ios::binary);
	char ch;
	ch='o';
	File.put(ch); //put the content of ch to the file
	File.seekg(ios::beg); //go to the beginning of the file
	File.get(ch); //read one character
	cout << ch << endl; //display it
	File.close();
}
``` 

## **How to write to a file?**

```
#include <iostream>
#include <fstream>
using namespace std;

int main() {
  // Creating and opening a text file
  ofstream MyFile("file_name.txt");

  // Write to the file
  MyFile << "Het, you just created your first file!";

  // Close the file
  MyFile.close();
}
``` 

## **Writing to a file and then reading it's data**

```
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  // Creating a text file
  ofstream MyFile("hey.txt");

  // Writing to the file
  MyWriteFile << "Hey, you just made your own file and then read it's data. That's so cool!";
 
  // Closing the file
  MyFile.close();

  // Creating a text string, which is used to output the text file
  string myText;

  // Read from the text file
  ifstream MyFile("hey.txt");

  // Using a while loop together with the getline() function to read the file line by line
  while (getline (MyFile, myText)) {
    // Output the text from the file
    cout << myText;
  }

  // Closing the file
  MyFile.close();
}

``` 
**Output:**

```
Hey, you just made your own file and then read it's data. That's so cool!
``` 

And that's all folks. You guys are now ready to fly on your own! Go and do some programming in C++ 😆

**Note:** See the examples of some basic C++ programs [here](https://github.com/AyeshaSahar/Cpp). See how file handling can be used in a project  [here](https://github.com/AyeshaSahar/Bank-Management-System). 

**Let's connect!**

✨ [Twitter](https://twitter.com/IAyeshaSahar)  

✨ [Github](https://github.com/AyeshaSahar)