File Input/Output in C++

 File Input/Output in C++


File Input/Output (I/O) is the process of reading from and writing to files on disk. In C++, you can use the fstream class to perform file I/O. Here's an example of using file I/O in C++:


c++


#include <iostream>

#include <fstream>


int main() {

  std::ofstream myfile("example.txt");

  myfile << "Hello, world!" << std::endl;

  myfile.close();


  std::ifstream input("example.txt");

  if (input.is_open()) {

    std::string line;

    while (std::getline(input, line)) {

      std::cout << line << std::endl;

    }

    input.close();

  }


  return 0;

}

In this example, we're using ofstream to create a new file called example.txt and write the string "Hello, world!" to it. We then close the file using the close method. We then use ifstream to open the same file for reading, and check if the file is open using the is_open method. If the file is open, we use std::getline to read each line of the file into a string, and then print it to the console. Finally, we close the file using the close method. When you run this program, you should see the message "Hello, world!" printed to the console.

No comments:

Post a Comment

The Importance of Cybersecurity in the Digital Age

 The Importance of Cybersecurity in the Digital Age Introduction: In today's digital age, where technology is deeply intertwined with ev...