C++ - Read and Write to a File


C++ - Read and Write to a File

CODE
#include <iostream> #include <fstream> using namespace std; int main() { string fileName = "data.txt"; //Write to a file ofstream f1(fileName); f1 << "This is a test line. 1\n"; f1 << "This is a test line. 2\n"; f1 << "This is a test line. 3\n"; f1 << "This is a test line. 4"; f1.close(); //Read the file line by line string line; ifstream f2(fileName); while (getline (f2, line)) { cout << line << endl; } f2.close(); //OUTPUT //This is a test line. 1 //This is a test line. 2 //This is a test line. 3 //This is a test line. 4 return 0; }

Comments