File Reader/Writer in C++
Below is an example of how you can use C++'s ofstream
and ifstream
classes to read from and write to a file.
// Include iostream and fstream #include int main() { // Replace "input.txt" and "output.txt" with your file names std::string inputFile = "input.txt"; std::string outputFile = "output.txt"; // Reading from a file using ifstream std::ifstream inputFileStream(inputFile); if (inputFileStream.is_open()) { std::string line; while (getline(inputFileStream, line)) { std::cout << "Read from file: " << line << std::endl; // You can process the line as needed here } inputFileStream.close(); } else { std::cerr << "Error reading from file." << std::endl; } // Writing to a file using ofstream std::ofstream outputFileStream(outputFile); if (outputFileStream.is_open()) { // Replace the following line with the content you want to write std::string contentToWrite = "Hello, this is written to the file!"; outputFileStream << contentToWrite << std::endl; std::cout << "Write to file: " << contentToWrite << std::endl; outputFileStream.close(); } else { std::cerr << "Error writing to file." << std::endl; } return 0; }