Unit 4 L11
Unit 4 L11
c++ streams,
c++ stream classes,
classes for file stream operations,
opening & closing files,
detection of end of file,
more about open(): file modes,
file pointer & manipulator,
sequential input & output operation,
updating a file: random access,
command line arguments
File
Stream: flow of data
RAM
Output stream
vari
able Input stream File
Data from variable to file- output stream
Data from file to variable-input stream
ios
istream ostream
>> <<
extraction
insertion
iostream
istream_withassign ostream_withassign
cin cout
OBJECT ORIENTED PROGRAMMING USING C++
1. ios/iostream
• ios stands for input output stream.
• This class is the base class for other classes in
this class hierarchy.
• This class contains the necessary facilities that
are used by all the other derived classes for
input and output operations.
ofstream ios::out
ifstream ios::in
Searches for the file and opens it in the write mode. If the
file is found, its content is overwritten. If the file is not
ios::out found, a new file is created. Allows you to write to the
file.
Searches for the file and opens it in the append mode i.e.
ios::app this mode allows you to append new data to the end of a
file. If the file is not found, a new file is created.
ios::trunc Searches for the file and opens it to truncate or deletes all
of its content(if the file is found).
ifstream infile(“salary”);
}
OBJECT ORIENTED PROGRAMMING USING C++
Reading Files: using getline()
How to process a file line by line in C++?
In C++, you may open a input stream on the file and use
the getline() function from the <string> to read content
line by line into a string and process them.
Ifstream fin;
fin.open("d://demo//file1.txt");
string str;
while(getline(fin,str))
{
cout<<str<<endl;
}
OBJECT ORIENTED PROGRAMMING USING C++
writing to a file
int main()
{
string line;
ifstream ini_file("original.txt“);
ofstream out_file( "copy.txt“);
if (ini_file && out_file)
{
while (getline(ini_file, line))
{
out_file << line << "\n";
}
cout << "Copy Finished \n";
}
else {
// Something went wrong
printf("Cannot read File");
}
ini_file.close();
out_file.close();
return 0;
}
Class
Data Members
Member
functions()
ifstream fin;
ofstream fout;
// file opening routine
fin.seekg(30); /*will move the get_pointer (in
ifstream) to byte number 30 in the file*/
fout.seekp(30); /* will move the put_pointer (in
ofstream) to byte number 30 in the file*/
ProgramName argument1
if(atoi(argv[1])%2==0)
printf("\nEVEN NUMBER\n");
else
printf("\nODD NUMBER\n");
return 0;
}
return 0;
}
Unit-4 End