Sie sind auf Seite 1von 15

FILES FOR DATA

HANDLING
Learning outcomes:

Check validity of file opening


Writing data onto files
Reading data from files
1

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Why need to learn about files?

So far, we have been using Input/Output console objects:


Input: using command cin to get data from keyboard.
Output: using command cout to write/display data or
results on computer monitor.
Problems using console Input/Output:
Need to key-in thousands of times if there is thousands of
data to be read

Cannot process data that are stored in a file.

Cannot store computed results for later use. Write them


by hand, on paper? What if the output is a long list?

Solution:
Use file processing/handling
2

What is a file in C++


programming?

In C++ programming, a file for reading can contain


data, whatever the data are, but in a certain ordered
format for easy handling (i.e., reading from and writing
to file).
A file for reading in C++ programming can also contain
an image which is used for display.
A file for writing can initially be an empty file, which
then is filled with data according to programmers need.
A file for writing can also be one which is already filled
with data, but later must be appended (i.e., added) with
new data.
EEE123, by Assoc Prof Dr Junita Mohamad Saleh

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Practical use of file

Examples:
You are given a file containing vehicle types and their
plate numbers for a project in which you have to separate
the plate numbers according to the type of vehicle, i.e.
cars, vans, motorcycle, lorry, etc.

A file containing info on all new students. You are


required to search in this file for female students only and
print out the names and matric numbers.

Advantages:
Accuracy Without data file processing features,
mistakes may occur in a work done using manual hands
and naked eyes.

Execution time/speed It takes less time to complete a


job with the help of a computer program, reading and
4
writing file.

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

How to implement file processing


with C++?
1.

2.

Declare preprocessor header file: #include <fstream>


Declare file object to be used for reading (i.e. input) and/or
writing (i.e. output)
Examples:
//Declare file object for reading only
//Command ifstream indicates input file
ifstream file_in (<filename>);
//Declare file object for writing only
//Command ofstream indicates output file

ofstream file_out (<filename>);


//Declare file object for reading & writing
//Command fstream indicates input and/or output file

fstream file_in_out (<filename>);

(cont)

How to implement file


processing with C++?

3.

4.

Check validity of file opening before using the file for


reading or writing.
Close files that have been opened when finish using them
using the format:
<file object name>.close()
E.g:
If a file for reading is opened using:
ifstream file_input(dataAssm.dat);
to close the file, use:
file_input.close ();

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

How to check for successful file


opening?

File opening is checked to avoid wasteful file


processing before a file is successfully opened.
Checking is done only after the file object has been
declared for reading and/or writing, by using the
command
<file object name>.fail()
If open file fails, an error message can be displayed.
e.g.
ifstream file_in (infile.dat);
if ( file_in.fail() )
cerr << ERROR: FILE OPEN FAILS;
7

Rules using files

A file can be opened and closed as many times as


needed.
However, if a file has been opened for writing, and
after use, the file has been closed, any new file that is
opened with the same filename as the previously
opened file will erase (reset) the content of the old file,
i.e. the old file will be overwritten with new info.
Any number of files can be opened for writing at the
same time. What differentiate them is their the
different file object names and filenames.
EEE123, by Assoc Prof Dr Junita
Mohamad Saleh

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

How to write onto file?

Writing information onto a file can simply be done by


replacing cout command with the file object name.

E.g.
ofstream file_out (outputfile.dat);
float Number1=45.4;
float Number2=99.8;
for (int i=1; i <= 5; i++)
file_out << Number1 <<\t<<Number2<< endl;
file_out.close();
9

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Type 1: How to read from file?


1.

Known datatype, known number of data to be read


Example: A lecturer knows the total number of students, and the
info is students matric number, which is of type int.
E.g. Read a file containing 10 students marks of type
float and display the marks.
Pseudocode:
Define constant value for number of data.
Declare file object , file_in, and open file.
Declare variable to store each students mark, marks.
while no_data <= 10,
file_in marks
display marks
10

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Type 2: How to read from file?


2.

Known datatype, unknown number of info to be read


Example: A lecturer does not know the total number of
students, but only knows that the marks are in float.
Use: for loop with an end-of-file condition.
E.g. Read a file of unknown number of students marks
of type float and display the marks.
Pseudocode:
Declare file object and open file.
Declare variable to store each students mark.
while (!file_in.eof() ) //NOT end-of-file
file_in marks
display marks
11

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Type 3: How to read from file?


3.

Unknown datatype (or mixed-type data), unknown


number of info to be read.
To loop line: use for or while with end-of-file
condition
To read info: use array_of_char[array_size], which
reads the entire line as array of characters. The
array size needs to be the maximum number of
characters that can form each line.
Pseudocode:
Declare file object and open file.
Declare array of characters to store each lines string.
while (!file_in.eof() ) //NOT end-of-file
read entire line ( file_in.getline(data,100) )
12

Example :
How to read unknown number of
data with unknown datatype?
Create a text data file by typing your name, and address lines
on separate lines. Save the file as name filein.dat.
Then, type the code segment below in a main program,
compile and run. NOTE: Do not forget to include header
file <fstream>
ifstream file_in (filein.dat);
char data[100];
// string data; // alternative method using string
for (int i=1; !file_in.eof(); i++) {
file_in.getline(data,100);
// getline(file_in,data); using string
cout << endl << "\t" << i << "\t" << data;}
cout << "\n\n\tEnd ofEEE123,
file!";
by Assoc Prof Dr Junita
Mohamad Saleh
13
file_in.close();

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

Type 4: How to read from file ?


4.

Unknown datatype (or mixed-type data), unknown number of


info to be read.
Read the entire line as string, including spaces and tabs. Using
this method, if any value needs to be a number, the string has to
be converted to number first.
To read each line: use getline(<str_variable>,<str_size>)
predefined function to read the entire line as string,
including spaces and tabs.
To repeat reading: use for loop with eof (end-of-file)
predefined function.
Pseudocode:
Declare file object and open file.
Declare array of character variable to store each lines string.
while NOT end-of-file (use !file_in.eof() )
read data line (use file_in.getline(data,100) )
display data
14

How to pass file to function?


Function prototype declaration
void Check_openFile(ofstream&);

Function call
Check_openFile(file_id);

Function header
void Check_openFile(ofstream& file_id);

EEE123, by Assoc Prof Dr Junita Mohamad Saleh

15

Das könnte Ihnen auch gefallen