C++ Files C-PLUS-PLUS

C++ Files  

C++ Files

C++ Files

The fstream library allows us to work with files.

To use the fstream library, including both the standard <iostream> AND the <fstream> header file:

Example

#include <iostream>
#include <fstream>

There are three objects included in the fstream library, which is used to create, write or read files:

Object/Data Type Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads, and writes to files

How to Create and Write To a File in C++

To create a file, use either the ofstream or fstream object, and specify the name of the file.

To write to the file, use the insertion operator (<<).

Example

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

int main() {
  // Create and open a text file
  ofstream MyFile("filename.txt");

  // Write to the file
  MyFile << "Files can be tricky, but it is fun enough!";

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

How to Read a File in C++

To read from a file, use either the ifstream or fstream object, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to the ifstream object) to read the file line by line, and to print the content of the file.

Example

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

int main () {
  // Create a text file
  ofstream MyWriteFile("filename.txt");

  // Write to the file
  MyWriteFile << "Files can be tricky, but it is fun enough!";
 
  // Close the file
  MyWriteFile.close();

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

  // Read from the text file
  ifstream MyReadFile("filename.txt");

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

  // Close the file
  MyReadFile.close();
}
 

Output:

Files can be tricky, but it is fun enough!

Download free E-book of C-PLUS-PLUS


#askProgrammers
Learn Programming for Free


Join Programmers Community on Telegram


Talk with Experienced Programmers


Just drop a message, we will solve your queries