How to Write to a Text File from a C++ Program

Writing to a text file from a C++ Program is very easy. In this example, which is part of my online course on Udemy titled “The Philosophy and Fundamentals of Computer Programming“, I will show you step by step, how to write to a text file from a sample C++ program that generates an array of 10 strings, and then it writes these values into a text file.

Note: In this example I’m using the c:\demosdirectory for exporting my file into.

The process of writing to a text file from a C++ program has five main steps in your code:

  1. Include the proper libraries
  2. Decide the data to be written into the file
  3. Open (create) the new file for writing
  4. Write the data
  5. Close the file

 

Include the proper libraries

The libraries to be included in the program are the below:

#include <iostream>
#include <string>
#include <fstream>

 


Learn Programming Today!

Check our online course: Introduction to Computer Programming for Beginners.

This course, will help you get started with C++, C, Python, SQL, Java, C# and learn more about Programming and the Programmer’s Mindset. Moreover, it will help you learn more about the main phases of the Software Development Lifecycle.

Introduction to Computer Programming for Beginners - Online Course
(Lifetime Access, Live Demos, Q&A, Completion Certificate)

This course, is definitely a must for beginners that are just starting out with computer Programming, but it is also useful for any technical level, since besides the main principles of programming, it also talks about the Programmer’s Mindset, that is the required skill set every great Programmer must have.

Learn More


 

Decide the data to be written into the file

This is something that is totally up to to you. In this example, I’m writing to the file, an array of 10 strings:

//define array of strings
string vehiclesList[10] = { "value0", "value1", "value2","value3", "value4", "value5","value6", "value7","value8", "value9" };

 

Open (create) the new file for writing

In this example, I’m writing into the file c:\demos\CPlusPlusSampleFile.txt, therefore, that is the file I’m opening/creating for writing:

//open file for writing
ofstream fw("c:\\demos\\CPlusPlusSampleFile.txt", std::ofstream::out);

 

Write the data

Prior to writing the data, first I’m checking if the file is actually open and ready for writing, then I proceed and write the data using the file handler and the bitwise left shift operators:

//check if file was successfully opened for writing
if (fw.is_open())
{
  //store array contents to text file
  for (int i = 0; i < arraySize; i++) {
    fw << vehiclesList[i] << "\n";
  }
  fw.close();
}
else cout << "Problem with opening file";

 

Close the file

Even though I closed the file after writing in the previous step, I also wanted to talk about this as a separate step, because I would like to stress out the importance of closing the file. This is very important, because if you don’t close the file, the operation will not be completed. Therefore, after writing all the data in the file, make sure that you close the file with the below command (based on my example):

//close the file after the writing operation is completed
fw.close();

 

Sample code for writing to a text file from a C++ program

Below, you can find the full sample code I prepared, for showcasing a simple example of writing an array of 10 strings into a text file.

// Sample C++ App that Writes Sample Data to Text File
//
// Created for the online course on Udemy: "The Philosophy and Fundamentals 
// of Computer Programming"
//
// Course URL: 
// https://www.udemy.com/course/philosophy-fundamentals-computer-programming/ 
//
// Author/Instructor: Artemakis Artemiou
//
// Disclaimer: This source code which is part of the online course on Udemy "The Philosophy and 
// Fundamentals of Computer Programming", is intended to be used only for demo purposes. Do not 
// use it for Production systems as it is simplified for demo purposes.
//
#include <iostream>
#include <string>
#include <fstream>

using namespace std;

int main()
{

  //define array of strings
  string vehiclesList[10] = { "value0", "value1", "value2","value3", "value4", "value5","value6", "value7","value8", "value9" };

  //get array size
  int arraySize = *(&vehiclesList + 1) - vehiclesList;

  //exception handling
  try {

    cout << "\nWriting  array contents to file...";

    //open file for writing
    ofstream fw("c:\\demos\\CPlusPlusSampleFile.txt", std::ofstream::out);

    //check if file was successfully opened for writing
    if (fw.is_open())
    {
      //store array contents to text file
      for (int i = 0; i < arraySize; i++) {
        fw << vehiclesList[i] << "\n";
      }
      fw.close();
    }
    else cout << "Problem with opening file";

  }
  catch (const char* msg) {
    cerr << msg << endl;
  }

  cout << "\nDone!";
  cout << "\nPress any key to exit...";
  getchar();

}

 

Watch the video tutorial: How to Write to a Text File Using C++

Learn More

 

Learn more about C++ and Programming

Check my online course on Udemy titled “Introduction to Computer Programming for Beginners” which offers the below educational benefits:

  • Define your relationship with Computer Programming.
  • Learn the ingredients, that is the required skill set for becoming a great Programmer.
  • Get started and then deep dive into the exciting world of Computer Programming.
  • Learn the basic Computer Programming Principles and Fundamentals such as: abstraction, algorithms, data structures, functions, inheritance, and more.
  • Learn more about Programming Languages; what are the factors that define a Programming Language as popular, how to choose a Programming Language, types of Databases, and more.
  • Learn  about the main phases of the Software Development Life Cycle which can help you efficiently design and develop robust enterprise-scale applications.
  • Learn how to start writing computer programs in the below Programming and Scripting Languages:
    • C#
    • SQL
    • Java
    • C
    • C++
    • Python
  • Via the Special Topics section, learn how to read and write to text files using any of the above Programming Languages.
Learn More

 

Featured Online Courses:

 

Read Also:

 

Rate this article: 1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)

Loading...

Reference: SQLNetHub.com (https://www.sqlnethub.com)

© SQLNetHub