0% found this document useful (0 votes)
57 views

CPP - Files - and - Streams - Dosya Açma-Kapama

The document discusses C++ file streams and how to read from and write to files. It introduces the fstream, ifstream, and ofstream classes that allow working with files. It covers opening, closing, writing to, and reading from files in C++ and provides examples of each. It also demonstrates reading data written to a file.

Uploaded by

Mike Thomson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
57 views

CPP - Files - and - Streams - Dosya Açma-Kapama

The document discusses C++ file streams and how to read from and write to files. It introduces the fstream, ifstream, and ofstream classes that allow working with files. It covers opening, closing, writing to, and reading from files in C++ and provides examples of each. It also demonstrates reading data written to a file.

Uploaded by

Mike Thomson
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 7

C++ Files and Streams 6 min read

31 July 2021

Till now, we have seen the use of iostream standard library that provides us with cin and cout
methods to take input and print output respectively. Here we will learn about another library to
handle files.

Files are used to store the data permanently in the storage device and a standard C++ library
called fstream allows us to work with files.

fstream Library
The fstream Library provides us with three classes that help us to read and write from the files
in C++. And these classes are:

fstream: This class generally represents a file stream. It is used to create files, write or
read data from or to the files.
ifstream: This class represents an input stream and used to read the data from the
files.
ofstream: This class represents an output stream and used to write the data to the
files.

Open a file
We can not perform any operation on file without opening it first. If you want to perform a write
operation on the file then open the file using fstream or ofstream objects. If you want to
perform a read operation on the file then open the file using ifstream object.

There is a function called open() which is a member of all three classes (fstream, ifstream,
and ofstream) and is used to open a file. The syntax to open a file is:

open (file_name, mode);

file_name: This simply indicates the name of the file to be opened.


mode: It defines the mode in which the file should be opened. It is opetaional. There are
several modes given below.

Mode Description

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
ios:: app Append mode. The output sent to the file is appended to it.

At end mode. It opens the file for the output then moves the read and write
ios::ate
control to the end of the file.

ios::in Input mode. It opens the file for reading.

ios::out Output mode. It opens the file for writing.

Truncate mode. If a file exists then before opening the file its contents are
ios::trunc
discarded.

Also while opening a file we can combine the above modes together using OR operator (|)
such as:

ofstream file;
file.open("file_name", ios::out | ios::trunc);

Default Modes:

As stated above the mode in an open() function is optional and if we do not provide the mode
then the following default mode will be assigned to the respective classes.

Class Mode

ifstream ios::in

ofstream ios::out

fstream ios::in | ios::out

Close a file
Once the program is terminated in C++, it automatically closes the opened files. However, it is
recommended to practice closing a file every time you open a file.

Just like a function open() is there to open a file, the fstream, ofstream, and ifstream objects
also have a close() function. The syntax is pretty simple.

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
void close();

Example: C++ program to open and close a file


#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
   fstream file;
   file.open("file.txt", ios::out);

   //check if file creation is failed or not


   if (!file)
   {
      cout << "File is not created!";
   }
   else
   {
      cout << "File is created successfully.";
      file.close();
   }
 
   return 0;
}

//Output
File is created successfully.

After successful execution of the above code, you may check the directory where your c++
program file is present, there you will find a new text file with file.txt name.

Writing to a file
Below is the example of C++ to write to a file. We will write to a text file called file.txt using the
stream insertion operator (<<). Here we use ofstream or fstream object instead of
the cout object.

Example: C++ to write in a file.

#include <iostream>
#include <fstream>

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
using namespace std;
 
int main()
{
  ofstream file("file.txt");
 
  //check if file is opened or not
  if (file.is_open())
  {
    file << "This is Simple2Code.com.\n";
    file << "Learn Programming Language.\n";
    file.close();
  }
  else
  {
    cout << "File failed to open";
  }
 
  return 0;
}

After successful execution of the program, you can open your file.txt and you will see the
following sentence inside that file.

This is Simple2Code.com.
Learn Programming Language.

Reading from a file


Below is the example of C++ to read from a file. We will from a text file called file.txt using the
stream extraction operator (>>). Here we use ifstream or fstream object instead of
the cin object.

Example: C++ to read from a file.

Now before running the program, you must create a file and write some text in it as for this
example, we created a file called file.txt and wrote the following text in it.
This is Simple2Code.com.
Learn Programming Language.

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
  string str;
  ifstream file("file.txt");
 
  //check if file is opened or not
  if (file.is_open())
  {
    while (getline(file, str))
    {
      cout << str << endl;
    }
 
    file.close();
  }
  else
  {
    cout << "File failed to open";
  }
 
  return 0;
}

After successful execution of the program, you will see the following output (String from
opened file.)

This is Simple2Code.com.
Learn Programming Language.

Example: Read and Write in C++


Here, we will see an example where we will write some data in a text file called file.txt and
then read those from the file using C++ FileStream. To write the data, we will take user input.

#include <iostream>
#include <fstream>
using namespace std;
 
int main()
{
  char data[100];
 
  //WRITE mode
  ofstream writeFile;
  writeFile.open("file.txt");
 
  cout << "Writing to a file:" << endl;
  cout << "Enter your name: ";
  cin.getline(data, 100);
 
  writeFile << data << endl;  //writing the entered data

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
 
  cout << "Enter your age: ";
  cin >> data;
  cin.ignore();
 
  writeFile << data << endl;  //writing the entered data
 
  writeFile.close();   //file closed
 
  //READ mode
  string str;
  ifstream readFile;
  readFile.open("file.txt");
 
  cout << "\nReading from a file:" << endl;
  while (getline(readFile, str))
  {
    cout << str << endl;
  }
 
  readFile.close();  //file closed
 
  return 0;
}

After Execution, a file name file.txt will be created and the following entered will be present in
that file.

Writing to a file:
Enter your name: John Markson
Enter your age: 29

Reading from a file:


John Markson
29

MORE
String Pattern Programs in C
In this tutorial, we will write various C pattern programs for String. Before that, you may go
through the following topics in C. for loop …

Read More

Java Program to Find pair of Integers in Array whose sum is


given Number

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com
In this tutorial, we will write a program to find a pair of elements from an array whose sum
equals a given number in java …

Read More

Program to Print Diamond Alphabet Patterns in C


In this tutorial, we will learn to write a C program to print Diamond patterns using
alphabets/characters. However, in this tutorial, we will create a …

Read More

Half Diamond Pattern in C using Alphabets


In this tutorial, we will learn and code the half diamond alphabet patterns in C programming
language. However, in this tutorial, we will create a …

Read More

Half Pyramid of Alphabets in C


In this tutorial, we will learn and code alphabet patterns in C programming language
specifically the Half pyramid of alphabets in C programming. However, in …

Read More

Inverted Half Pyramid Pattern of Alphabets in C


In this tutorial, we will write a C program to print half Pyramid using alphabets/characters.
Before that, you may go through the following topic in …

Read More

 CPlusPlus Tutorial

Convert web pages and HTML files to PDF in your applications with the Pdfcrowd HTML to PDF API Printed with Pdfcrowd.com

You might also like