C++ || How To Read An Entire File Into A String & Write A String To A File Using C++
The following is a module with functions which demonstrates how to write a string to a file and read an entire file to a string using C++.
The functions demonstrated on this page uses fstream to read and write data to and from a file.
1. Read All Text
The example below demonstrates the use of ‘Utils::readAllText‘ to open a text file, read all the text in the file into a string, and then close the file.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
// Read All Text // Declare path std::string path = "C:\\Users\\Name\\Desktop\\text.txt"; // Read the contents of the file at the specified path std::string contents = Utils::readAllText(path); // Display contents std::cout << contents; // example output: /* ... The contents of the file */ |
2. Write All Text
The example below demonstrates the use of ‘Utils::writeAllText‘ to create a new file, write a specified string to the file, and then close the file. If the target file already exists, it is overwritten.
1 2 3 4 5 6 7 8 9 10 11 12 |
// Write All Text // Declare path std::string path = "C:\\Users\\Name\\Desktop\\text.txt"; // Declare file contents std::string contents = "Kenneth, Jennifer, Lynn, Sole"; // Save contents to the specified path Utils::writeAllText(path, contents); // ... Contents are written to the file |
3. Utils Namespace
The following is the Utils Namespace. Include this in your project to start using!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 9, 2020 // Taken From: http://programmingnotes.org/ // File: Utils.h // Description: Handles general utility functions // ============================================================================ #pragma once #include <string> #include <fstream> #include <limits> #include <stdexcept> namespace Utils { /** * FUNCTION: readAllText * USE: Opens a text file, reads all the text in the file into a string, * and then closes the file * @param path: The file to open for reading * @return: A string containing all text in the file */ std::string readAllText(const std::string& path) { std::ifstream infile(path); if (infile.fail()) { throw std::invalid_argument{ "Unable to read file at path: '" + path + "'" }; } infile.ignore(std::numeric_limits<std::streamsize>::max()); std::streamsize size = infile.gcount(); infile.clear(); infile.seekg(0, infile.beg); std::string contents(size, ' '); infile.read(&contents[0], size); return contents; } /** * FUNCTION: writeAllText * USE: Creates a new file, writes the specified string to the file, * and then closes the file. If the target file already exists, it * is overwritten * @param path: The file to write to * @param contents: The string to write to the file * @return: N/A */ void writeAllText(const std::string& path, const std::string& contents) { std::ofstream outfile(path); if (outfile.fail()) { throw std::invalid_argument{ "Unable to write file at path: '" + path + "'" }; } outfile << contents; } }// http://programmingnotes.org/ |
4. More Examples
Below are more examples demonstrating the use of the ‘Utils‘ Namespace. Don’t forget to include the module when running the examples!
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 |
// ============================================================================ // Author: Kenneth Perkins // Date: Dec 9, 2020 // Taken From: http://programmingnotes.org/ // File: program.cpp // Description: The following demonstrates the use of the Utils Namespace // ============================================================================ #include <iostream> #include <string> #include <exception> #include "Utils.h" void display(const std::string& message); int main() { try { // Declare path std::string path = "C:\\Users\\Name\\Desktop\\text.txt"; // Declare file contents std::string contents = "Kenneth, Jennifer, Lynn, Sole"; // Save contents to the specified path Utils::writeAllText(path, contents); // Read the contents of the file at the specified path std::string contents2 = Utils::readAllText(path); // Display contents display(contents2); } catch (std::exception& e) { display("\nAn error occurred: " + std::string(e.what())); } std::cin.get(); return 0; } void display(const std::string& message) { std::cout << message << std::endl; }// http://programmingnotes.org/ |
QUICK NOTES:
The highlighted lines are sections of interest to look out for.
The code is heavily commented, so no further insight is necessary. If you have any questions, feel free to leave a comment below.
Leave a Reply