Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • C++ Data Types
  • C++ Input/Output
  • C++ Arrays
  • C++ Pointers
  • C++ OOPs
  • C++ STL
  • C++ Interview Questions
  • C++ Programs
  • C++ Cheatsheet
  • C++ MCQ
  • C++ Projects
  • C++ Exception Handling
  • C++ Memory Management
Open In App
Next Article:
How to Read From a File in C++?
Next article icon

How to Read File into String in C++?

Last Updated : 21 May, 2024
Comments
Improve
Suggest changes
Like Article
Like
Report

In C++, file handling allows us to read and write data to an external file from our program. In this article, we will learn how to read a file into a string in C++.

Reading Whole File into a C++ String

To read an entire file line by line and save it into std::string, we can use std::ifstream class to create an input file stream for reading from the specified file with a combination of std::getline to extract the lines from the file content that can be concatenated and stored in a string variable.

Approach

  • Open the file using std::ifstream file(filePath).
  • Use the is_open() method to check if the file was opened successfully, if not print error message and return.
  • Use a loop with std::getline(file, line) to read each line of the file into a string and print the populated string.
  • Close the file stream.

C++ Program to Read a File into String

The below program demonstrates how we can read the content of a file into a std::string line by line in C++.

C++
// C++ Program to demonstrate how to Read a File into String #include <fstream> #include <iostream> #include <string> using namespace std;  int main() {      // get the filepath     string filePath = "myFile.txt";      // Open the file using ifstream     ifstream file(filePath);      // confirm file opening     if (!file.is_open()) {         // print error message and return         cerr << "Failed to open file: " << filePath << endl;          return 1;     }      // Read the file line by line into a string     string line;     while (getline(file, line)) {         cout << line << endl;     }      // Close the file     file.close();      return 0; } 


Output

File Content:   Hi, Geek!  Welcome to gfg.  Happy Coding ;)

Time Complexity: O(n), here n is total number of characters in the file.
Auxiliary Space: O(n)

 

 


Next Article
How to Read From a File in C++?

S

sonijaiog3d
Improve
Article Tags :
  • C++ Programs
  • C++
  • cpp-file-handling
  • C++ File Programs
  • CPP Examples
Practice Tags :
  • CPP

Similar Reads

  • How to input a comma separated string in C++?
    Given an input string which is comma-separated instead of space, the task is to parse this input string in C++.First, let us understand what difference does it create if the input string is comma-separated. Taking input a whitespace-separated stringTaking input a whitespace-separated string in C++ i
    2 min read
  • How to Read Input Until EOF in C++?
    In C++, EOF stands for End Of File, and reading till EOF (end of file) means reading input until it reaches the end i.e. end of file. In this article, we will discuss how to read the input till the EOF in C++. Read File Till EOF in C++The getline() function can be used to read a line in C++. We can
    2 min read
  • How to Read a File Line by Line in C++?
    In C++, we can read the data of the file for different purposes such as processing text-based data, configuration files, or log files. In this article, we'll learn how to read a file line by line in C++. Read a File Line by Line in C++We can use the std::getline() function to read the input line by
    2 min read
  • How to Read a File Using ifstream in C++?
    In C++, we can read the contents of the file by using the ifstream object to that file. ifstream stands for input file stream which is a class that provides the facility to create an input from to some particular file. In this article, we will learn how to read a file line by line through the ifstre
    2 min read
  • How to Read From a File in C++?
    Reading from a file means retrieving the data stored inside a file. C++ file handling allows us to read different files from our C programs. This data can be taken as input and stored in the program for processing. Generally, files can be classified in two types: Text File: Files that contains data
    4 min read
  • How to Convert wstring to int in C++?
    In C++, std::wstring is a type of string where each character is of a wide character type. These types of strings can be used to store the numerical strings which can then be converted to their corresponding type. In this article, we will see how to convert a wstring to an int in C++. Input: wstr =
    2 min read
  • How to Reverse a String in C++?
    Reversing a string means replacing the first character with the last character, second character with the second last character and so on. In this article, we will learn how to reverse a string in C++. Examples Input: str = "Hello World"Output: dlroW olleHExplanation: The last character is replaced
    2 min read
  • How to Reverse a String in Place in C++?
    In C++, reversing a string is a basic operation in programming that is required in various applications, from simple and complex algorithms. Reversing a string in place involves changing the characters of the string directly without using input-dependent additional storage. In this article, we learn
    2 min read
  • How to Match a Pattern in a String in C++?
    In C++, strings are sequences of characters stored in a char array. Matching a pattern in a string involves searching for a specific sequence of characters (the pattern) within a given string. In this article, we will learn how to match a pattern in a string in C++. Example: Input:Text: "GeeksForGee
    2 min read
  • How to Read a Line of Input Text in C++?
    In C++, we often need to take input from the user by reading an input text line by line but the cin method only takes input till whilespace. In this article, we will look at how to read a full line of input in C++. For Example, Input: This is a text.Output: Entered Text: This is a text.Taking a Line
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences