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:
Include the proper libraries
Decide the data to be written into the file
Open (create) the new file for writing
Write the data
Close the file
Include the proper libraries
The libraries to be included in the program are the below:
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.
(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.
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++
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.
Artemakis Artemiou is a seasoned Senior Database and AI/Automation Architect with over 20 years of expertise in the IT industry. As a Certified Database, Cloud, and AI professional, he has been recognized as a thought leader, earning the prestigious Microsoft Data Platform MVP title for nine consecutive years (2009-2018). Driven by a passion for simplifying complex topics, Artemakis shares his expertise through articles, online courses, and speaking engagements. He empowers professionals around the globe to excel in Databases, Cloud, AI, Automation, and Software Development. Committed to innovation and education, Artemakis strives to make technology accessible and impactful for everyone.
Views:19,373
We use cookies on our website to give you the most relevant experience by remembering your preferences and repeat visits. By clicking “Accept All”, you consent to the use of ALL the cookies. However, you may visit "Cookie Settings" to provide a controlled consent. Read More
This website uses cookies to improve your experience while you navigate through the website. Out of these, the cookies that are categorized as necessary are stored on your browser as they are essential for the working of basic functionalities of the website. We also use third-party cookies that help us analyze and understand how you use this website. These cookies will be stored in your browser only with your consent. You also have the option to opt-out of these cookies. But opting out of some of these cookies may affect your browsing experience.
Necessary cookies are absolutely essential for the website to function properly. These cookies ensure basic functionalities and security features of the website, anonymously.
Cookie
Duration
Description
cookielawinfo-checkbox-analytics
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Analytics".
cookielawinfo-checkbox-functional
11 months
The cookie is set by GDPR cookie consent to record the user consent for the cookies in the category "Functional".
cookielawinfo-checkbox-necessary
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookies is used to store the user consent for the cookies in the category "Necessary".
cookielawinfo-checkbox-others
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Other.
cookielawinfo-checkbox-performance
11 months
This cookie is set by GDPR Cookie Consent plugin. The cookie is used to store the user consent for the cookies in the category "Performance".
viewed_cookie_policy
11 months
The cookie is set by the GDPR Cookie Consent plugin and is used to store whether or not user has consented to the use of cookies. It does not store any personal data.
Functional cookies help to perform certain functionalities like sharing the content of the website on social media platforms, collect feedbacks, and other third-party features.
Performance cookies are used to understand and analyze the key performance indexes of the website which helps in delivering a better user experience for the visitors.
Analytical cookies are used to understand how visitors interact with the website. These cookies help provide information on metrics the number of visitors, bounce rate, traffic source, etc.
Advertisement cookies are used to provide visitors with relevant ads and marketing campaigns. These cookies track visitors across websites and collect information to provide customized ads.