0% found this document useful (0 votes)
52 views3 pages

C++ File I/O: Writing and Reading Text

The document discusses different methods for writing to and reading from text files in C++, including: 1) Writing to a file using the << operator or put() method and reading using the >> operator or get() method. 2) Opening a file stream using ifstream or ofstream, writing/reading data, then closing the file stream. 3) Specific examples show opening a file, writing/reading a string, character, or line of text, and closing the file.

Uploaded by

Yash Chaturvedi
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)
52 views3 pages

C++ File I/O: Writing and Reading Text

The document discusses different methods for writing to and reading from text files in C++, including: 1) Writing to a file using the << operator or put() method and reading using the >> operator or get() method. 2) Opening a file stream using ifstream or ofstream, writing/reading data, then closing the file stream. 3) Specific examples show opening a file, writing/reading a string, character, or line of text, and closing the file.

Uploaded by

Yash Chaturvedi
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

Writing to a text file

 Using operator(<<)

// Creating and writing to a file - C++


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ()
{
clrscr();
ofstream file;
[Link] ("[Link]");
file <<"Please write this text to a file.\nThis text is written using C++\n";
[Link]();
getch();
}
 Using put()

// Creating and writing to a file - C++


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
#include<stdio.h>
#include<string.h>
void main ()
{ clrscr();
char ch[100]="We are writing in string.";
ofstream file;
[Link] ("[Link]",ios::out);
int len=strlen(ch);
for(int i=0;i<len;i++)
{
[Link](ch[i]);
}
[Link]();
getch();
}
Reading from a text file
 Using operator(>>)
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ()
{ clrscr();
char ch[100];
ifstream f;
[Link] ("[Link]");
while (![Link]())
{
f>>ch;
cout<<ch;
}
[Link]();
getch();
}
 Using get()
#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ()
{
clrscr();
char ch;
ifstream file;
[Link] ("[Link]");
while (![Link]()) //or while (file)
{
[Link](ch);
cout<<ch;
}
[Link]();
getch();
}
 Using getline()

// Reading a binary file - C++


#include <iostream.h>
#include <fstream.h>
#include <conio.h>
void main ()
{ clrscr();
char ch[80];
ifstream file;
[Link] ("[Link]");
while (file)
{
[Link](ch,80);
cout<<ch;
}
[Link]();
getch();
}

You might also like