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:\demos
directory 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:
#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.
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.
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.
Featured Online Courses:
- AI Essentials: A Beginner’s Guide to Artificial Intelligence
- SQL Server 2022: What’s New – New and Enhanced Features
- Working with Python on Windows and SQL Server Databases
- Introduction to Azure Database for MySQL
- Boost SQL Server Database Performance with In-Memory OLTP
- Introduction to Azure SQL Database for Beginners
- Essential SQL Server Administration Tips
- SQL Server Fundamentals – SQL Database for Beginners
- Essential SQL Server Development Tips for SQL Developers
- Introduction to Computer Programming for Beginners
- .NET Programming for Beginners – Windows Forms with C#
- SQL Server 2019: What’s New – New and Enhanced Features
- Entity Framework: Getting Started – Complete Beginners Guide
- Data Management for Beginners – Main Principles
- A Guide on How to Start and Monetize a Successful Blog
Read Also:
- How to Connect to SQL Server from Visual C++
- What is Abstraction in Object Oriented Programming?
- How to Establish a Simple Connection from a C# Program to SQL Server
- The timeout period elapsed prior to obtaining a connection from the pool
- Closing a C# Application (including hidden forms)
- Changing the startup form in a C# project
- Using the C# SqlParameter Object for Writing More Secure Code
- Cannot implicitly convert type ‘string’ to ‘System.Windows.Forms.DataGridViewTextBoxColumn
- Using the C# SqlParameter Object for Writing More Secure Code
- Tip of the Week No.15 – Main Data Structures in C#
- How to Build a Simple Image Viewer with .NET WinForms and C# in Visual Studio
Rate this article:
Reference: SQLNetHub.com (https://www.sqlnethub.com)
© SQLNetHub
Artemakis Artemiou, a distinguished Senior Database and Software Architect, brings over 20 years of expertise to the IT industry. A Certified Database, Cloud, and AI professional, he earned the Microsoft Data Platform MVP title for nine consecutive years (2009-2018). As the founder of SQLNetHub and GnoelixiAI Hub, Artemakis is dedicated to sharing his knowledge and democratizing education on various fields such as: Databases, Cloud, AI, and Software Development. His commitment to simplicity and knowledge sharing defines his impactful presence in the tech community.