#programming [[Programming]] 3/22/2024 9:39 pm I realized earlier that I do not know how to read or write files with C++. I remember learning how to do those things with Java way back in high school, but I never learned how to in C++. This note is a recap of tonight's quick attempt to learn those skills. I used [this blog post](https://www.udacity.com/blog/2021/05/how-to-read-from-a-file-in-cpp.html) as the primary reference. I'm tired so I just wanted something actionable and easy to follow. I'm working on getting more familiar with using libraries and header files, and not just using namespace std like I used to. For this project, only three header files were needed: ``` #include <iostream> #include <fstream> #include <string> ``` This part creates an object that will be used for reading the contents of a plain text file: ``` std::ifstream fileRead; fileRead.open("c++Read.txt"); ``` The text from the aforementioned text file: ``` This is a document for testing my C++ program. I will write some text here, then read it to a C++ program and output it on the screen. I hope it works well! ``` I then made some string variables to take the contents of the text file. ``` std::string fileContents; std::string eachLine; ``` The variables needed are pretty straightforward. The first way I tried involved reading the file characters individually, but that method stopped upon encountering the first bit of white space. The final method read the entire file, first by character then by line. ``` if( fileRead.is_open() ){ char currentChar; while( fileRead ){ std::getline (fileRead, eachLine); //currentChar = fileRead.get(); //std::cout << currentChar; std::cout << eachLine << "\n"; } }else{ std::cout << "Cannot open file.\n"; } ```