c++ fstream read line write ,creat file program

To read and write lines from a file in C++ using the fstream library, you can follow these steps:

  1. Include the necessary header file: Begin by including the <fstream> header file, which provides the necessary classes and functions for file input and output.

  2. Declare an instance of fstream: Create an instance of the std::fstream class to handle file operations. You can choose a name for your instance, such as file.

  3. Open the file: Use the open() function of the std::fstream class to open the file. This function takes the file name as a parameter and opens the file in the desired mode, such as std::ios::in for read mode or std::ios::out for write mode. For example, to open a file named "example.txt" for reading, you can use file.open("example.txt", std::ios::in).

  4. Check if the file opened successfully: After opening the file, you should check if the file was opened successfully. You can do this by using the is_open() function of the std::fstream class. This function returns true if the file was opened successfully and false otherwise.

  5. Read lines from the file: To read lines from the file, you can use the getline() function of the std::fstream class. This function takes two parameters: a string variable to store the line, and a delimiter character to indicate where to stop reading the line. For example, to read a line from the file and store it in a string variable named line, you can use getline(file, line).

  6. Write lines to the file: To write lines to the file, you can use the << operator with the file instance. For example, to write a line to the file, you can use file << line.

  7. Close the file: After you have finished reading from or writing to the file, it is important to close it using the close() function of the std::fstream class. This ensures that any changes made to the file are properly saved.

Here is an example that demonstrates these steps:

#include <fstream>
#include <iostream>

int main() {
    std::fstream file;
    file.open("example.txt", std::ios::in);

    if (file.is_open()) {
        std::string line;
        while (getline(file, line)) {
            std::cout << line << std::endl;
        }
        file.close();
    } else {
        std::cout << "Failed to open the file." << std::endl;
    }

    return 0;
}

In this example, the program opens the file "example.txt" for reading, reads each line from the file using getline(), and then prints the lines to the console. The file is closed using close() after the reading is done.