Documente Academic
Documente Profesional
Documente Cultură
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
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 ...
Unit 3
Unit 3
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
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
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
Unit 3
Unit 3
Unit 3
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
Unit 3
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.
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();
}