
A to Z About File Input Output in C++
For various reason we need to process file while processing a C++ program. We normally use file input output in C++ if you need to save the output for later. Or if we don’t want to type the input values again and again. However using file input output in C++ or any other programming is always a good practice. Here I have explained A to Z about file.

Why We Need to Use File in Programming?
Reasons to use file in programming:
- To save time for taking input again and again.
- To keep your data clean and well formed.
- To save your output for further needs.
- To use your output for any database operation. (i.e. Excel, CSV, MS Access)
- To have some knowledge how file operations work inside OS.
What is Input in C++?
In computer programming, Input are those value which are taken from keyboard, file or any other source while running a program. The following example code takes an input using scanf function and another input using cin directive. Here scanf means scanning function and cin means console input directive.
#include<bits/stdc++.h> using namespace std; int main(){ int a, b; scanf("%d", &a); cin>>b; }
What is Output in C++?
In computer programming, An output is a combination of one or more value that comes from a program after running some functions inside it. The following example code prints two value taken as input in previous example. One using printf function another using cout directive. Here printf is the printing function in C/C++ and cout is directive for console output in C++.
#include<bits/stdc++.h> using namespace std; int main(){ int a, b; scanf("%d", &a); cin>>b; printf("%d", a); cout<<b; }
What is file in C++?
In C++, a file is an object containing several texts inside it. An object is always declared with a class name. There are three classes in C++ that performs file operation. They are:
- Output File Stream: Used to open a file for writing output to the file. Output File Stream Class object is written as:
ofstream myfile;
- Input File Stream: Used to open a file for reading input from the file. Input File Stream Class object is written as:
ifstream myfile;
- File Stream: Used to open a file for both writing output to the file and reading input from the file. File Stream Class object is written as:
fstream myfile;
What is Filestream in C++?
A filestream, fstream or file stream is a segment of a file which is processed at a time. A file can be of thousands megabyte. But computer program cannot process the whole file at once. The file should be divided into some streams to process it for input and output. That is why we use filestream in C++ programming.
How to Create a File in C++?
C++ allows to create a file only when you are going to write something on the file. If you are going to read something from the file that means you already have a file containing some data. The following example creates a file named “example.txt”.
#include<bits/stdc++.h> using namespace std; int main(){ ofstream myfile; myfile.open("example.txt"); }
How to Open File in C++?
To perform any file operation you need to open a file first. If you have an existing file then you can open in. If you don’t have an existing file a new file will be created. Opening a file is similar to creating a file in output stream. In input stream there is no way to create a new file but opening a file is same to output stream. The following example open “file1.txt” in output file stream and open “file2.txt” in input file stream.
#include<bits/stdc++.h> using namespace std; int main(){ ofstream myfile; myfile.open("file1.txt"); ifstream myfile; myfile.open("file2.txt"); }
How to Write Output to File in C++?
To write output in file in C++ you need to use output file stream. Existing a file is not mandatory in that case. If you have a file existing the program will write in that. If the file doesn’t exist the program will create a file and write in the file. If the location of the file is not defined that means you addresses the file only by the name it will be located in the same folder of the program. The following example writes “Hello World” in the file “example.txt”.
#include<bits/stdc++.h> using namespace std; int main(){ ofstream myfile; myfile.open("example.txt"); myfile<<"Hello World"; }
How to Read Input from File in C++?
To read input from a file you need to use input file stream. In this case, you must need to have a file existed. If you don’t have a file with the specified name that is an error. You can read an integer, a double, a character, a string or a line from the file. The following example reads and prints the first word in the file. If you have run the previous example then your output should be “Hello”.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); string s; myfile>>s; cout<<s; }
How to Close File in C++?
After completing your operations with a file you should always close your file. If file is not closed correctly same data may be lost or corrupted. So, to ensure security you must close all opened file. The following example close the file associated with myfile object.
#include<bits/stdc++.h> using namespace std; int main(){ fstream myfile; myfile.open("example.txt"); myfile<<"Hello World"; myfile.close(); }
How to Open a File for Both Read and Write in C++?
To open file for both read and write you need to use file stream (fstream). To secure your data you must need to close your file after each operation and reopen before next operation. Otherwise you can use two different file. The following example write “Hello World” in “newfile.txt” and read the first word from “example.txt”.
#include<bits/stdc++.h> using namespace std; int main(){ fstream myfile; myfile.open("newfile.txt"); myfile<<"Hello World"; myfile.open("example.txt"); string s; myfile>>s; cout<<s; }
What is File Opening Mode in C++?
File opening mode is the directives that defines what will be performed with the file and how that will take place. Some common file modes and there supported functionalities are given in the below table.
Mode | Operations |
ios::in | Input mode open file for input operations |
ios::out | Input mode open file for output operations |
ios::binary | Binary mode open file input and output operations performed independently |
ios::ate | At End mode open file in such way that the previous content is inaccessible. The start of the file is considered at end. |
ios::app | Append mode does the same job of At End in case of output operations only. That means output is appended at the end of the file. |
ios::trunc | Truncate mode truncate or format file contents before performing any operation. |
How to Combine File Opening Modes in C++?
File Opening modes can be combined using bitwise OR ( | ) operator. For example if you want to open you file for both input and output and don’t want to loss previous data then you can do this.
myfile.open("example.txt", ios::out | ios::in | ios::ate);
What are Default Modes for Filestream Classes in C++?
Three different filestream classes has three different default value for file opening mode. It is clear that those classes are differentiated just because of different file opening mode. The default modes for filestream classes in C++ are given in the table below.
Class | Default Mode |
ofstream | ios::out |
ifstream | ios::in |
fstream | ios::out | ios::in |
How to Check is a File Opened or Closed?
Sometimes opening file is very important. Because opening file can consume time which may change values of certain instances. In some cases closing file is also important in the middle of the program. That means reopening a file. If we do not do so, some data may be corrupted. The following example checks whether file is opened or not.
#include<bits/stdc++.h> using namespace std; int main(){ ofstream myfile; myfile.open("newfile.txt"); myfile<<"Hello World"; if (myfile.is_open())cout<<"File is Opened"; else cout<<"File is Closed"; }
What are File State Flags in C++?
There are some Boolean function to define the state of a file. Those functions are called State Flags at once. State flags are required in certain conditions. The following table shows most common state flags and there roles in C++.
Flag | Condition |
bad() | If any read or write operation fails then this flag returns true. |
fail() | It returns true is case of condition in bad() including data type mismatch. |
eof() | It is true when the input pointer reach at the end of file. |
good() | It is true when all the above are false. |
How to Read an Integer from File in C++?
To read an integer from a file you need to declare an integer variable. If your file have integer data it can be read easily otherwise the operation will be failed. The following example read an integer from file.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); int a; myfile>>a; cout<<a; }
How to Read a String from File in C++?
Words are combination of characters. We can read characters and combine them as word or string later or we can directly read as string. This is an example of reading a string.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); string s; myfile>>s; cout<<s; }
How to Read Line By Line from File in C++?
Taking one by one data reduces performance of the code. So, we may need to read line by line from file. In C++ you can read data liny by line using stringstream. The following example shows how to read a line from file in C++.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); int num; string s; getline(myfile, s); stringstream strstm(s); while(strstm >> num){ cout<<num<<endl; } return 0; }
How to Read Multiple Line from File in C++?
To read multiple line from file the process is similar. But in that case we need to continue one additional loop considering whether more line exists or not. The following example reads all lines from a file.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); int num; string s; while(getline(myfile, s)){ stringstream strstm(s); while(strstm >> num){ cout<<num<<endl; } } return 0; }
How to Get Value from Specific Position of File in C++?
To get value from specific position of file you need to use file pointer. File pointer function have two part. First one is the position and the second one is the positioning method. Basically these functions change the file read-write pointer location. These functions don’t return a value. The following lines are some examples of positioning functions.
myfile.seekg(0, ios::beg); //Start. Deafult Pointer.
myfile.seekg(n, ios::beg); //n'th byte forward from start.
myfile.seekg(n, ios::end); //n'th byte backward from end.
myfile.seekg(0, ios::end); //End of file. Default after applying ios::ate mode.
The following program gives output a string or substring skipping first 6 byte.
#include<bits/stdc++.h> using namespace std; int main(){ ifstream myfile; myfile.open("example.txt"); myfile.seekg(6, ios::beg); string s; myfile>>s; cout<<s; }
Here all the things that may be required for file processing in C++ are given. If you have any further things to know please comment.