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:
Include the necessary header file: Begin by including the
<fstream>
header file, which provides the necessary classes and functions for file input and output.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 asfile
.Open the file: Use the
open()
function of thestd::fstream
class to open the file. This function takes the file name as a parameter and opens the file in the desired mode, such asstd::ios::in
for read mode orstd::ios::out
for write mode. For example, to open a file named "example.txt" for reading, you can usefile.open("example.txt", std::ios::in)
.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 thestd::fstream
class. This function returnstrue
if the file was opened successfully andfalse
otherwise.Read lines from the file: To read lines from the file, you can use the
getline()
function of thestd::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 namedline
, you can usegetline(file, line)
.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 usefile << line
.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 thestd::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.