Download as pdf or txt
Download as pdf or txt
You are on page 1of 11

Mechanical Engineering

Lab Report 02
Title:
File Handling in C++
1ST SEMESTER

Submitted To: Engr. Ali Hassan


Class: ME-13 B Group: N/A
Submitted By
Sr.No Name (Roll.no) Data Viva Total
Presentation
1 Muhammad
Usama Tariq
(366451)
Objectives:
1. Writing some text to a file.
2. Reading from a file.
3. Read and write example.

Theory:
Stream :
Stream is a general term used for the flow of data from source to a destination. The
process of input data from source is known as reading. The process of outputting data is
known as writing.
Stream classes are defined in the header files. The objects stream classes are
used to control flow of data.

If stream :
This is used to perform input operations on data files on the disk. The objects of
this stream is used to read file on the disk.

Of stream :
This stream is used to perform the output operations on data files on the disk. The
objects of this stream are used to write data from memory on the disk.

Fstream :
The stream is used to both input & output operations on files on the disk.
File operation modes :
The data files can be opened in different modes. These modes are
defined in “ios” class. The resolution operator (::) is used between the “ios” and the mode
code.
Some of them required are :
ios :: in Open files in input mode to read data from the file. The data can only be read but
cant be written in the file.
ios :: out Opens files in output mode to write data on the file. If the file of the same name
already exists on the disk, all data in the file is erased and a new file is opened.

The “cerr” object :


The “cerr” object is used for making error messages. This object is similar
to “cout” object. The difference is that cerr is unbuffered and is displayed immediately.
Lab Work :
Q1) Program to enter Name and CMS ID in the txt file.
#include<fstream>
#include<iostream>
#include<string>
using namespace std;
int main() {
string a,b;
cout<<"Please enter your name :";
getline(cin , a);
cout<<"Please enter your CMS ID = ";
getline(cin , b);
ofstream myfile;
myfile.open("name.txt");
myfile<<"My name is "<<a<<"\nCMS ID = "<<b;
return 0;
}

Q2 ) Program to print Hello world in a text file.


#include<iostream>
#include<fstream>
using namespace std;
int main() {
ofstream myfile;
myfile.open("2nd.txt");
myfile<<"Hello World";
myfile.close();
return 0;
}
Q3 ) Program to write data to the file and then reading from it.
#include<iostream>
#include<fstream>
#include<string>
using namespace std;
int main() {
string a,data;
int b;
cout<<"Enter your name : ";
getline(cin , a);
cout<<"Enter your age : ";
cin>>b;
cout<<"\nWriting to the file..........";
ofstream out;
out.open("2nd.txt");
out<<"Name : "<<a<<"\nAge : "<<b;
out.close();
cout<<"\nReading from the file........"<<endl;
ifstream in;
in.open("2nd.txt");
while(getline(in , data)){
cout<<data<<endl;
}
in.close();

return 0;

}
Q4 )
#include<iostream> //Required for cerr
#include<fstream> //Required for ifstream, ofstream
using namespace std;
int main()
{
//Define file streams for input and output.
ifstream fin("sensor.txt");
ofstream fout("checkedSensor.txt");
//Check for possible errors.
if(fin. fail())
{
cerr << "could not open input file sensor.dat\n";
exit(1);
}
if(fout. fail())
{
cerr << "could not open output file checkedSensor.dat\n";
exit(1);
}
//All files are open.
double t, motion;
int count(0);
fin >> t >> motion;
while(!fin.eof())
{
++count;
//Write valid data to output file.
if(t >= 0 && motion >= 0)
{
fout << t << " " << motion << endl;
}
//Write invalid data to standard error output.
else
{
cerr << "Bad data encountered on line"
<< count << endl
<< t << " " << motion << endl;
}
//Input next data pair.
fin >> t >> motion;
}//end while

//close all files.


fin.close();
fout.close();
return 0;
}

Input file :

Output :
Home Task :
Q1) Program 5.4 :
/*---------------------------------------------------------------*/
/* Program chapter5_6 */
/* This program reads an html file, and writes the text */
/* without the tags to a new file. */
#include<iostream> //Required for cin, cout, cerr.
#include<fstream> //Required for ifstream, ofstream.
#include<string> //Required for string.
using namespace std;
int main()
{
// Declare objects.
char character;
bool text_state(1);
string infile, outfile;
ifstream html;
ofstream htmltext;
// Prompt user for name of input file.
cout << "enter the name of the input file :";
cin >> infile;
// Prompt user for name of output file.
cout << "enter the name of the output file :";
cin >> outfile;
// Open files.
html.open(infile.c_str());
if(html.fail())
{
cerr << "Error opening input file\n";
exit(1);
}
htmltext.open(outfile.c_str());
// Read first character from html file.
html.get(character);
while(!html.eof())
{
// Check state.
if(text_state)
{
if(character == '<') // Beginning of a tag.
text_state=0; // Change States.
else
htmltext << character; // Still text, write to the file
}
else
{
// Command state, no output required.
if(character == '>') // End of tag.
text_state = 1; // Change States.
}
// Read next character from html file.
html.get(character);
}
html.close();
htmltext.close();
return 0;
}

Input file :
Output :

Q2) Program 5.7 :


/* Program chapter5_8 */
/* */
/* This program computes a linear model for a set */
/* of altitude and ozone mixing ratio values. */
#include <iostream> //Required for cin, cout
#include <fstream> //Required for ifstream
#include <string> //Required for string
using namespace std;
int main()
{
// Declare and initialize objects.
int count(0);
double x, y, first, last, sumx(0), sumy(0), sumx2(0),
sumxy(0), denominator, m, b;
string filename;
ifstream zone1;
cout << "Enter name of input file:";
cin >> filename;
// Open input file.
zone1.open(filename.c_str());
if(zone1.fail())
{
cerr << "Error opening input file\n";
exit(1);
}
// While not at the end of the file,
// read and accumulate information.
zone1 >> x >> y;
while ( !zone1.eof() )
{
++count;
if (count == 1)
first = x;
sumx += x;
sumy += y;
sumx2 += x*x;
sumxy += x*y;
zone1 >> x >> y;
}
last = x;
// Compute slope and y-intercept.
denominator = sumx*sumx - count*sumx2;
m = (sumx*sumy - count*sumxy)/denominator;
b = (sumx*sumxy - sumx2*sumy)/denominator;
// Set format flags
cout.setf(ios::fixed);
cout.precision(2);
// Print summary information.
cout << "Range of altitudes in km: \n";
cout << first << " to " << last << endl << endl;
cout << "Linear model: \n";
cout << "ozone-mix-ratio = " << m << " altitude + "
<< b << endl;
// Close file and exit program.
zone1.close();
return 0;
}
/*---------------------------------------------------------*/

Input file :
Output :

Q3) Differentiate between pseudo code and algorithm.


Pseudo code :
Pseudo code describes the flow of the program. It is the basis of “algorithm”
itself. It is aimed to simplify the programming language for the beginners so that humans can
understand it without having any prior knowledge to the programming language. It can be
written in day to day language and every one can have a different style of writing it.

Algorithm :
Algorithm is a step-wise procedure written to give a solution to the particular
problem. It is the basis of any “programming language”. Algorithm are the steps that contain
specific selections, sequences and iterations. It can analyze every problem and can propose a
step by step solution. It is simple and easy to understand for a person who knows about the
language and executes on the available resources.

You might also like