Sunteți pe pagina 1din 30

Unit 3

Text files
Definition
Declaration
Opening and closing
Reading
Writing
Unit 3: C++ Files
Exercises
Programming 2
Binary files
Definition
Declaration, opening
and closing
Read
Write
Exercises

Errors

2013-2014
Index

Unit 3
1 Text files
Definition
Text files
Definition
Declaration
Declaration
Opening and closing
Opening and closing
Reading
Writing
Reading a text file (1/2)
Exercises
Writing a text file
Binary files
Definition
Exercises
Declaration, opening
and closing
Read
2 Binary files
Write
Exercises
Definition
Errors Declaration, opening and closing
Reading a binary file
Writing a binary file
Exercises
3 Managing read/write errors
What is a text file?

Unit 3

Text files
Definition
Declaration
A text file is also called file with format
Opening and closing
Reading It only contains printable characters
Writing
Exercises
A printable character is a character with an ASCII code
Binary files
Definition
greater or equal to 32.
Declaration, opening
and closing
Read
What is ASCII code? It’s a code which maps each
Write
Exercises
character to a number (computers only store numbers).
Errors Text file examples: C++ source code, a webpage
(HTML), a makefile, . . .
Declaration of file variables

Unit 3

Text files
Definition
Declaration
Opening and closing
Reading
Writing
Exercises
To use them, add #include <fstream> :
Binary files ifstream fich_read; (read only)
Definition
Declaration, opening
ofstream fich_write; (write only)
and closing
Read
fstream fich_read_write; (unusual in text files)
Write
Exercises

Errors
Opening and closing (1/2)

Unit 3

Text files Opening modes: read, write, read/write, append


Definition
Declaration Files can be opened in C++ using “open”.:
Opening and closing
Reading
Writing const char nombre[]="mifichero.txt";
Exercises fichero.open(nombre,ios::in);
Binary files
Definition
Declaration, opening
When the filename is a string, it must be converted into
and closing
Read an array of characters using the function c_str().
Write
Exercises C++ opening modes:
Errors read ios::in
write ios::out
read/write ios::in | ios::out (fstream)
append ios::out | ios::app
Opening and closing (2/2)

Unit 3

Shortened version:
Text files ifstream fl("ifi.txt"); // by default, ios::in
Definition
Declaration
Opening and closing ofstream fe("ofi.txt"); // ios::out
Reading
Writing
Exercises

Binary files
Definition How to check whether the file was opened? How to
Declaration, opening
and closing close it?
Read
Write
Exercises
if (fichero.is_open())
{
Errors
// it can be read now ...

fichero.close(); // close the file


}
else // opening error
Detection of the end of file

Unit 3

Using the method “eof”:


Text files ifstream fi;
Definition
...
Declaration
Opening and closing while (!fi.eof() ...)
Reading
Writing
Exercises How does it work?
Binary files
Definition
When any data (character, integer, etc.) is asked to be
Declaration, opening
and closing read but there is nothing else in the file, the method
Read
Write returns “true”
Exercises

Errors Warning: after reading the last valid data, it returns


“false’ ’ again, therefore ...
It’s necessary to make an extra read (which may return
non-valid data that can be ignored) to force the end of
file detection.
Reading lines (1/2)

Unit 3

Text files ...


Definition
Declaration
if (fi.is_open())
Opening and closing {
Reading
getline(fi,s); // ’s’ is string
Writing
Exercises // fi.getline(cad,tCAD); // ’cad’ is char []
Binary files
while (!fi.eof())
Definition {
Declaration, opening // do something with ’s’
and closing
Read
Write getline(fi,s);
Exercises
}
Errors
fi.close();
}
Reading lines (2/2)

Unit 3

What happens if the last line of the file doesn’t end with
‘\n’? then it’s lost and discarded!!
Text files
Definition
Declaration
...
Opening and closing if (fi.is_open())
Reading
{
Writing
Exercises s="";
Binary files
getline(fi,s);
Definition while (!fi.eof() || s.length()!=0)
Declaration, opening {
and closing
Read // do something with ’s’
Write
Exercises
s=""; // initialize ’s’
Errors getline(fi,s);
}

fi.close();
}
Reading single characters

Unit 3

Text files
Definition ...
Declaration if (fi.is_open())
Opening and closing
Reading
{
Writing c = fi.get();
Exercises
while (!fi.eof())
Binary files {
Definition
// do something with ’c’
Declaration, opening
and closing
Read
c = fi.get();
Write
Exercises }
Errors
fi.close();
}
Reading more than one variable

Unit 3
Files are actually “streams”, therefore they behave like
cin and cout
Text files
Definition #include <fstream>
Declaration
...
Opening and closing
Reading ifstream fi;
Writing int numentero; double numreal;
Exercises

Binary files fi.open("mifichero.txt",ios::in);


Definition
Declaration, opening
if (fi.is_open())
and closing {
Read
Write
fi >> numentero;
Exercises while (!fi.eof())
Errors
{
fi >> numreal;
// do something with ’numentero’ and ’numreal’
fi >> numentero; // "extra" lecture?
}
fi.close();
}
Writing a text file

Unit 3

Text files
Definition
Declaration
Opening and closing
ofstream fo;
Reading
Writing fo.open("mifichero.txt",ios::out);
Exercises
if (fo.is_open())
Binary files {
Definition
Declaration, opening
fo << "Un numero entero: " << numentero << endl;
and closing ...
Read
Write
Exercises fo.close();
Errors }
Exercises (1/5)

Unit 3

Text files
Definition Exercise 1
Declaration
Opening and closing
Reading
Make a program for reading a file called “fichero.txt”,
Writing
Exercises
writing in another file “FICHERO2.TXT” the content of the
Binary files
input file with all its letters in uppercase.
Definition
Declaration, opening
and closing
Example:
Read
Write
Exercises
fichero.txt FICHERO2.TXT
Errors Hola, mundo. HOLA, MUNDO.
Como estamos? COMO ESTAMOS?
Adios, adios... ADIOS, ADIOS...
Exercises (2/5)

Unit 3

Exercise 2
Text files Design a program for reading two text files, “f1.txt” and
Definition
Declaration
“f2.txt”, writing on the screen the lines that differ in both
Opening and closing
Reading
files, adding “< ” if the line corresponds to “f1.txt”, and
Writing
Exercises
“ >” if it corresponds to “f2.txt”.
Binary files
Definition
Example:
Declaration, opening
and closing f1.txt f2.txt
Read
Write hola, mundo. hola, mundo.
Exercises
como estamos? como vamos?
Errors adios, adios... adios, adios...
The output should be:
< como estamos?
> como vamos?
Exercises (3/5)

Unit 3

Exercise 3
Text files
Definition
Declaration
Develop a function called “finfichero” receiving two
Opening and closing
Reading
arguments: the first one must be a positive integer n, and
Writing
Exercises
the second the name of a text file. The function must print
Binary files on the screen the last n lines of the given file.
Definition
Declaration, opening
and closing
Example:
Read
Write $ finfichero(3,"cadenas.txt")
Exercises

Errors
with several words
unapalabra
muuuuchas palabras, muchas, muchas...
Exercises (4/5)

Unit 3

Text files Exercise 3 (continue)


Definition
Declaration
Opening and closing
Two possible solutions:
Reading
Writing
1 Using “brute force”: reading all the file to count the
Exercises
number of lines and then read it again to write the last n
Binary files
Definition lines
Declaration, opening
and closing PROBLEM: what happens if the file has
Read
Write 100000000000000 lines?
Exercises

Errors
2 Use a string vector of size n storing at every time the
last n lines (although at the beginning, it will contain
less than n lines)
Exercises (5/5)

Unit 3

Exercise 4
Text files
Definition
Given two text files “f1.txt” and “f2.txt”, in which each
Declaration
Opening and closing
line is a series of numbers separated by “:”, and assuming
Reading
Writing
that the lines are in ascending order by the first number,
Exercises
make a function to read both files line by line writing in the
Binary files
Definition file “f3.txt” the common lines, like in the following
Declaration, opening
and closing example:
Read
Write
Exercises Ejemplo:
Errors f1.txt f2.txt f3.txt
10:4543:23 10:334:110 10:4543:23:334:110
15:1:234:67 12:222:222 15:1:234:67:881:44
17:188:22 15:881:44 20:111:22:454:313
20:111:22 20:454:313
What is a binary file?

Unit 3

Text files It’s also called file without format


Definition
Declaration
Opening and closing
In a binary file, data are stored as they are in memory,
Reading
Writing
without being converted into characters.
Exercises
Usually, each element to be stored is written using a
Binary files
Definition structure (struct)
Declaration, opening
and closing
Read
When elements are stored using structures, it’s
Write
Exercises
possible to directly access the n-th element without
Errors reading the n − 1 previous data.
Text files have sequential access, whereas binary files
have direct (random) access.
Declaration, opening and closing binary files

Unit 3

Variable declaration like in text files:


Text files ifstream fbl; // file for reading
Definition
Declaration
ofstream fbe; // file for writing
Opening and closing
Reading
Writing
Exercises
File opening: The “ios::binary” flag must be added
Binary files fbl.open("mifichero.dat", ios::in | ios::binary);
Definition
Declaration, opening
fbe.open("mifichero.dat", ios::out | ios::binary);
and closing
Read
Write
Exercises File closing: like in text files, using close:
Errors
fbl.close();

Other opening modes:


read/write ios::in | ios::out | ios::binary
append ios::out | ios::app | ios::binary
Reading a binary file

Unit 3

typedef struct { ... } TIPOCIUDAD;


Text files ...
Definition
Declaration
Opening and closing TIPOCIUDAD ciudad;
Reading
Writing
Exercises
fbl.open("mifichero.dat",ios::in | ios::binary);
if (fbl.is_open())
Binary files
Definition
{
Declaration, opening fbl.read((char *)&ciudad, sizeof(ciudad));
and closing
Read
while (!fbl.eof())
Write {
Exercises // process ’ciudad’
Errors
fbl.read((char *)&ciudad, sizeof(ciudad));
}
fbl.close();
}
Direct access to an element

Unit 3

The position of an element in the file can be calculated in


Text files
Definition
function of the size (using sizeof) of the previous data
Declaration
Opening and closing if (fbl.is_open())
Reading
Writing
{
Exercises // positioning for reading the third element
Binary files fbl.seekg ( (3-1)*sizeof(ciudad), ios::beg);
Definition fbl.read( (char *)&ciudad, sizeof(ciudad) );
Declaration, opening
and closing
...
Read }
Write
Exercises

Errors
Other references for the position:
fbl.seekg( pos, ios::cur) from the current position
fbl.seekg( pos, ios::end) from the end of the file

Warning: pos can also be negative


Writing a binary file

Unit 3

Text files typedef struct { ... } TIPOCIUDAD;


Definition
Declaration
...
Opening and closing
Reading
TIPOCIUDAD ciudad;
Writing
Exercises ofstream fbe;
Binary files
Definition fbe.open("mifichero.dat",ios::out | ios::binary);
Declaration, opening if (fbe.is_open())
and closing
Read {
Write // fill ’ciudad’
Exercises

Errors fbe.write((const char *)&ciudad, sizeof(ciudad));


...
}
Direct access to an element for writing

Unit 3

Text files
Definition
The method seekp must be used for positioning the writing
Declaration
Opening and closing
pointer instead of seekg (which is only for reading).
Reading
Writing if (fbe.is_open())
Exercises
{
Binary files // positioning to write the third element
Definition
Declaration, opening
fbe.seekp ( (3-1)*sizeof(ciudad), ios::beg);
and closing fbe.write( (const char *)&ciudad, sizeof(ciudad) );
Read
Write
...
Exercises }
Errors
Warning: if the position specified with seekp does not exist
in the file, then the file is enlarged to write the data.
Reading/writing structures using arrays of
characters
Unit 3

Text files
Definition To store an structure containing strings in a binary file, an
Declaration
Opening and closing array of characters must be used (never a C++ string) . It
Reading
Writing can be necessary to cut the string:
Exercises

Binary files
Definition char cad[tcREG];
Declaration, opening
and closing string s;
Read
Write
Exercises
...
strncpy(cad,s.c_str(),tcREG-1);
Errors
cad[tcREG-1]=’\0’; // strncpy does not add \0 if not present
Information about the current position

Unit 3

Text files
Definition
Declaration
Opening and closing
The current position in bytes of the read or write
Reading
Writing
pointers can be seen using the functions tellg and
Exercises tellp respectively. For example:
Binary files
Definition // Locate the read pointer at the end
Declaration, opening
and closing f.seekg(0,ios::end);
Read
Write
Exercises
// Calculate the total number of elements in the file
cout << f.tellg()/sizeof(myStruct) << endl;
Errors
Exercises

Unit 3

Exercise 5
Text files Given a binary file called “alumnos.dat” which stores
Definition
Declaration student structures with the next information for each
Opening and closing
Reading student:
Writing
Exercises
dni array of 10 characters
Binary files
Definition
apellidos array of 40 characters
Declaration, opening
and closing
nombre array of 20 characters
Read turno integer
Write
Exercises

Errors
Write a program for printing on the screen the DNI of all the
students belonging to the group number 7.

Extension: write a program to exchange the students of


groups 4 and 8 (groups range from 1 to 10).
Exercises

Unit 3

Exercise 6
Text files
Definition
Declaration
Given the file “alumnos.dat” from the previous exercise,
Opening and closing
Reading
make a program for converting the name and surname of
Writing
Exercises
the fifth student to uppercase, and then write it again to the
Binary files file.
Definition
Declaration, opening
and closing
Exercise 7
Read
Write Make a program to build the file “alumnos.dat” from the
Exercises

Errors
data stored in a text file “alu.txt’, in which each field (dni,
name, etc) is in a different line. Consider that the filename,
dni, name and surname may be longer than the length
specified for the binary file, therefore they might be cut.
Exercises

Unit 3

Exercise 8
Text files
Definition
Declaration
Write a program to automatically assign students to 10
Opening and closing
Reading
practice groups. Each student will be assigned to the group
Writing corresponding to his/her DNI last number (those ending with
Exercises

Binary files
0 will be assigned to the group 10). The student data is
Definition
Declaration, opening
stored in a file “alumnos.dat” with the same structure
and closing
Read
seen in previous exercises.
Write
Exercises
The student assignation must be done reading the file once
Errors (in one pass), without storing it in memory. At each step, the
information for a student will be read, the group will be
calculated, and the structure will be stored in the same
position.
Read/write errors (1/2)

Unit 3

Text files
Definition
Declaration
They can occur in text and binary files
Opening and closing
Reading Although they are very unusual, they must be managed
Writing
Exercises It’s recommended to check for possible errors after
Binary files
Definition
each read/write
Declaration, opening
and closing
The method fail can be used to find them (although
Read
Write
there are other ways):
Exercises
if (fi.fail() && !fi.eof()) // read error
Errors
...
Read/write errors (2/2)

Unit 3

if (fi.is_open())
Text files {
Definition
bool error=false;
Declaration
Opening and closing getline(fi,s);
Reading if (fi.fail() && !fi.eof()) error=true;
Writing
Exercises
while (!error && !fi.eof())
{
Binary files
Definition
// do something with ’s’
Declaration, opening
and closing
Read
getline(fi,s);
Write if (fi.fail() && !fi.eof()) error=true;
Exercises }
Errors
if (error)
// error message
fi.close();
}

S-ar putea să vă placă și