Files

You might also like

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

See discussions, stats, and author profiles for this publication at: https://www.researchgate.

net/publication/348960289

Files in C++

Presentation · February 2021


DOI: 10.13140/RG.2.2.26135.09127

CITATIONS READS

0 7,245

1 author:

Tarfa Hamed
University of Mosul
38 PUBLICATIONS 263 CITATIONS

SEE PROFILE

All content following this page was uploaded by Tarfa Hamed on 02 February 2021.

The user has requested enhancement of the downloaded file.


Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Files and Streams in C++

• C++ provides some classes to perform output and input of


characters to/from files
• Programmers use the iostream standard library, which
provides cin and cout methods for reading from standard input
and writing to standard output respectively.
• In this lecture we are going to learn how to read from and write
to a file.
• This requires another standard C++ library called fstream, which
defines three new data types.

No. Data Type & Description

ofstream
1.
This data type represents the output file stream and is used to create files
and to write information to files.

ifstream
2.
This data type represents the input file stream and is used to read
information from files.

fstream
3. This data type represents the file stream generally, and has the
capabilities of both ofstream and ifstream which means it can create
files, write information to files, and read information from files.

• To perform file processing in C++, header files <iostream> and


<fstream> must be included in your C++ source file.

1
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

Opening a File
• A file must be opened before you can read from it or write to it.
Either ofstream or fstream object may be used to open a file for
writing.
• And ifstream object is used to open a file for reading purpose
only.
• Following is the standard syntax for open() function, which is a
member of fstream, ifstream, and ofstream objects.

void open(const char *filename, ios::openmode mode);

• Here, the first argument specifies the name and location of the
file to be opened and the second argument of the open() member
function defines the mode in which the file should be opened.

No. Mode Flag & Description

1. ios::app
Append mode. All output to that file to be appended to the end.

2. ios::ate
Open a file for output and move the read/write control to the end of
the file.

3. ios::in
Open a file for reading.

4. ios::out
Open a file for writing.

5. ios::trunc
If the file already exists, its contents will be removed before opening
the file.

2
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

• You can combine two or more of these values by ORing them


(use the OR operation | ) together.
• For example if you want to open a file in write mode and want to
truncate it in case that already exists, following will be the syntax:
ofstream outfile;
outfile.open("file.dat", ios::out | ios::trunc );

• Similar way, you can open a file for reading and writing purpose
as follows:
fstream afile;
afile.open("file.dat", ios::out | ios::in );

Closing a File
• When a C++ program terminates it automatically flushes all the
streams, release all the allocated memory and close all the opened
files.
• But it is always a good practice that a programmer should close
all the opened files before program termination.
• Following is the standard syntax for close() function, which is a
member of fstream, ifstream, and ofstream objects.

File_name.close();

Writing to a File
• You can write information to a file from your program using the
stream insertion operator (<<) just as you use that operator to
output information to the screen.
• The only difference is that you use an ofstream or fstream object
instead of the cout object.

3
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

• The following example is a program for writing some text to a


file:

#include <iostream>
#include <fstream>
using namespace std;

int main () {
ofstream myfile;
myfile.open("example.txt");

myfile << "This is a line.\n";


myfile << "This is another line.\n";
myfile.close();

return 0;
}

Reading from a File


• Similarly, you can read information from a file into your program
using the stream extraction operator (>>) just as you use that
operator to input information from the keyboard.
• The only difference is that you use an ifstream or fstream object
instead of the cin object.
• The following example is a program for reading some text from
a file:

#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
string line;
ifstream myfile ("example.txt");
if (myfile.is_open())
{
while ( getline (myfile,line) )
{
4
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

cout << line << '\n';


}
myfile.close();
}

else cout << "Unable to open file";

return 0;
}

Read and Write Example


• Following is the C++ program which opens a file in reading and
writing mode.
• After writing information entered by the user to a file named
afile.dat, the program reads information from the file and outputs
it onto the screen:
#include <fstream>
#include <iostream>
using namespace std;

int main () {

string data;
// open a file in write mode.
ofstream outfile;
outfile.open("afile.dat",ios::out );

cout << "Writing to the file" << endl;


cout << "Enter your name: ";
cin>>data;

// write inputted data into the file.


outfile << data << endl;

int age;
cout << "Enter your age: ";
cin >> age;

// again write inputted data into the file.


outfile << age << endl;

// close the opened file.


outfile.close();

5
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

// open a file in read mode.


ifstream infile;
infile.open("afile.dat",ios::in);

cout << "Reading from the file" << endl;


while ( getline (infile,data) )
{
// write the data at the screen.
cout << data << endl;
}
// close the opened file.
infile.close();

return 0;
}

• When the above code is compiled and executed, it produces the


following sample input and output:

Writing to the file


Enter your name: Ali
Enter your age: 9
Reading from the file
Ali
9

• The above example makes use of additional functions like


getline() function to read the line from a file.

HW1: Write a CPP program that reads items names and items prices
of 50 items from KB and stores them in a file (prices.txt) line-by-line.
After that, the program reads the previous file and writes the items that
are priced over $100 in a separate file (prices_100.txt).

Example of prices.txt contents:


Rice 125
Tomato paste 50
Cooking Oil 30
Flour 120

The contents of prices_100.txt will be:


Rice 125
Flour 120

6
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

HW2: Write a CPP program that reads a line consists of an unknown


number of words. The program then writes each word on a separate line
in a file named (words.txt). Hint: use getline to read the line instead of
cin.

HW3: Write a CPP program to read students information from a file


named (f1.csv). The file contains information for 100 students. Each
student has one line consists of:
Name(string), prg(int), logic(int), math(int), level(string). The above
parts are separated by commas (,).
The program is required to write the following information on a second
filed named (smmary.txt):
a- The highest mark in programming (prg).
b- The lowest mark in logic.
c- The average of math marks.
After that, the program needs to create two more files named
(passed.txt) and (failed.txt) respectively. The first file contains all the
students who passed in all subjects. The second file contains all the
students who failed in one or more subjects.

HW4: Write a function to count the number of blank spaces in a text


file named "input.txt"

HW5: Write a function to count number of words in a text file named


"story.txt".

HW6: Write a C++ program to print the count of word (the) as a


separate word in a file named transcript.txt. For example, if the content
of the file transcript.txt is:
There was a monkey in the zoo.
The monkey was very naughty.
Then the output of the program should be 2
HW7: Assume that you have a text file named file1.dat contains some
text written into it, write a function named vowelwords(), that reads the
file file1.dat and creates a new file named file2.dat, to contain only
those words from the file file1.dat which start with a lowercase vowel
(i.e., with 'a', 'e', 'i', 'o', 'u').
7
Department of Computer Science, College of Computer Science and Mathematics, University of Mosul, Iraq

For example, if the file file1.dat contains:


Carry umbrella and overcoat when it rains
Then the file file2.dat shall contain:
umbrella and overcoat it

View publication stats

You might also like