Thanks to visit codestin.com
Credit goes to www.scribd.com

0% found this document useful (0 votes)
19 views1 page

C++ Reading A Text Into A File

This C++ program demonstrates how to write text to a file called "sample.txt" using the fstream class, then read the text back from the file. It opens the file for writing, writes the text "ABCD.", closes the file. It then reopens the file for reading, reads each character into a variable, and prints it to the console until the end of the file is reached.

Uploaded by

Paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
19 views1 page

C++ Reading A Text Into A File

This C++ program demonstrates how to write text to a file called "sample.txt" using the fstream class, then read the text back from the file. It opens the file for writing, writes the text "ABCD.", closes the file. It then reopens the file for reading, reads each character into a variable, and prints it to the console until the end of the file is reached.

Uploaded by

Paul
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 1

Write and read text in/from file

//C++ program to write and read text in/from file.


#include <iostream>
#include <fstream>

using namespace std;

int main()
{
fstream file; //object of fstream class

//opening file "sample.txt" in out(write) mode


file.open("sample.txt",ios::out);

if(!file)
{
cout<<"Error in creating file!!!"<<endl;
return 0;
}

cout<<"File created successfully."<<endl;


//write text into file
file<<"ABCD.";
//closing the file
file.close();

//again open file in read mode


file.open("sample.txt",ios::in);

if(!file)
{
cout<<"Error in opening file!!!"<<endl;
return 0;
}

//read untill end of file is not found.


char ch; //to read single character
cout<<"File content: ";

while(!file.eof())
{
file>>ch; //read single character from file
cout<<ch;
}

file.close(); //close file

return 0;
}

You might also like