File I/O and Classes in C++

Chapter 12

1. What capability does the fstream data type provide that the ifstream and ofstream data type do not?
The fstream data type allows both reading and writing, while the ifstream data type allows only for reading, and the ofstream data type allows only for writing.

2. Which file access flag do you use to open a file when you want all output written to the end of the file’s existing contents?
ios::app

3. Assume that the file data.txt already exists, and the following statement executes. What happens to the file?

fstream file (“data.txt”, ios::out);

Its contents are erased. (In other words, the file is truncated.)

4. How do you combine multiple file access flags when opening a file?
By using the | operator.

5. Should file stream objects be passed to functions by value or by reference? Why?
By reference because the internal state of file stream objects changes with most every operation. They should always be passed to functions by reference to ensure internal consistency.

6. Under what circumstances is a file stream object’s ios::hardfail bit set? What member function reports the state of this bit?
When an unrecoverable error has occurred.

7. Under what circumstances is a file stream object’s ios::eofbit bit set? What member function reports the state of this bit?
When the end of the file has been encountered. The eof member function reports the state of this bit.

8. Under what circumstances is a file stream object’s ios::badbit bit set? What member function reports the state of this bit?
When an invalid operation has been attempted.

9. How do you read the contents of a text file that contains whitespace characters as part of its data?
By using the getline member function.

10. What arguments do you pass to a file stream object’s write member function?
Two arguments: The starting address of the section of memory that is to be written to the file, and the number of bytes that are to be written.

11. What arguments do you pass to a file stream object’s read member function?
Two arguments: The starting address of the section of memory where the data will be stored, and the number of bytes to read.

12. What type cast do you use to convert a pointer from one type to another?
reinterpret_cast

13. What is the difference between the seekg and seekp member functions?
The seekg function moves a file’s write position, and the seekp function moves a file’s read position.

14. How do you get the byte number of a file’s current read position? How do you get the byte number of a file’s current write position?
Use tellg to get the byte number of the current read position and use tellp to get the byte number of the current write position.

15. If a program has read to the end of a file, what must you do before using either the seekg or seekp member functions?
Call the file object’s clear member function.

16. How do you determine the number of bytes that a file contains?
First use the seekg member function to move the read position to the last byte in the file. Then use the tellg function to get the current byte number of the read position.

17. How do you rewind a sequential-access file?
Use the seekg member function to move the read position back to the beginning of the file.

18. The ____ file stream data type is for output files, input files, or files that perform both input and output.
fstream

19. If a files fails to open, the file stream object will be set to ____
0

20. The same formatting techniques used with ____ may also be used when writing data to a file.
cout

21. The ____ function reads a line of text from a file.
getline

22. The ____ member function reads a single character from a file.
get

23. The ____ member function writes a single character from a file.
put

24. ____ files contain data that is unformatted and not necessarily stored as ASCII text.
Binary

25. ____ files contain data formatted as ____
Text, ASCII text

26. A(n) ____ is a complete set of data about a single item and is made up of ____
Record, fields

27. In C++, ____ provide a convenient way to organize data into fields and records.
Structures

28. The ____ member function writes “raw” binary data to a file.
write

29. The ____ member function reads “raw” binary data from a file.
read

30. The ____ operator is necessary if you pass anything other than a pointer-to-char as the first argument of the two functions mentioned in questions 26 and 27.
Typecast

31. In ____ file access, the contents of the file are read in the order they appear in the file, from the file’s start to its end.
Sequential

32. In ____ file access, the contents of a file may be read in any order.
Random

33. The ____ member function moves a file’s read position to a specified byte in the file.
seekg

34. The ____ member function moves a file’s write position to a specified byte in the file.
seekp

35. The ____ member function returns a file’s current read position.
tellg

36. The ____ member function returns a file’s current write position.
tellp

37. The ____ mode flag causes an offset to be calculated from the beginning of a file.
ios::beg

38. The ____ mode flag causes an offset to be calculated from the end of a file.
ios::end

39. The ____ mode flag causes an offset to be calculated from the current position in the file.
ios::cur

40. A negative offset causes the file’s read or write position to be moved ____ in the file from the position specified by the mode.
Backward

41. Write a statement that defines a file stream object named places. The object will be used for both output and input.
fstream places (“places.dat”, ios::in | ios::out);

42. Write two statements that use a file stream object named people to open a file named people.dat. (Show how to open the file with a member function and at the definition of the file stream object.) The file should be opened for output.

ofstream people (“people.dat”, ios::out);
people.open (“people.dat”, ios::out);

43. Write two statements that use a file stream object named pets to open a file named pets.dat. (Show how to open the file with a member function and at the definition of the file stream object.) The file should be opened for input.

pets.open (“pets.dat”, ios::in);
fstream pets (“pets.dat”, ios::in);

44. Write two statements that use a file stream object named places to open a file named places.dat. (Show how to open the file with a member function and at the definition of the file stream object.) The file should be opened for both input and output.

fstream places (“places.dat”, ios::in | ios::out);
places.open (“places.dat”, ios::in | ios::out);

45. Write a program segment that defines a file stream object named employees. The file should be opened for both input and output (in binary mode). If the file fails to open, the program segment should display an error message.

fstream employees;
employees.open (“emp.dat”, ios::in | ios::out | ios::binary);
if (!employees)
cout

46. Write code that opens the file data.txt for both input and output, but first determines if the file exists. If the file does not exist, the code should create it, then open it for both input and output.

fstream dataFile;
// Determine whether the file exists.
dataFile.open (“data.txt”, ios::in);
if (dataFile.fail () )
{
// The file does not exist, so create it.
dataFile.open (“data.txt”, ios::out);
dataFile.close();
}
// Now open the file for processing.
dataFile.open (“data.txt”, ios::in | ios::out);

47. Write code the determines the number of bytes contained in the file associated with the file stream object datafile.

dataFile.seekg (0L, ios::end);
numBytes = dataFile.tellg();
cout

48. The infoFile file stream object is used to sequentially access data. The program has already read to the end of the file. Write code that rewinds the file.

infoFile.clear();// Clear the eof flag.
infoFile.seekg (0L, ios::beg);// Rewind the read position.

49. Different operating systems have different rules for naming files.
True

50. fstream objects are only capable of performing file output operations.
False

51. ofstream objects, by default, delete the contents of a file if it already exists when opened.
True

52. ifstream objects, by default, create a file if it doesn’t exist when opened.
False

53. Several file access flags may be joined by using the | operator.
True

54. A file may be opened in the definition of the file stream object.
True

55. A file may be opened in the definition of the file stream object, no mode flags may be specified.
False

56. A file stream object’s fail member function may be used to determine if the file was successfully opened.
True

57. The same output formatting techniques used with cout may also be used with file stream objects.
True

58. The >> operator expects data to be delimited by whitespace characters.
True

59. The getline member function can be used to read text that contains whitespaces.
True

60. It is not possible to have more than one file open at once in a program.
False

61. Binary files contain unformatted data, not necessarily stored as text.
True

62. Binary is the default mode in which files are opened.
False

63. The tellp member function tells a file stream object which byte to move its write position to.
False

64. It is possible to open a file for both input and output.
True

65. fstream file (ios::in | ios::out);
file.open (“info.dat”);
if (!file)
{
cout }

File should be opened as:
fstream file (“info.dat”, ios:in | ios:out);

or

fstream file;
file.open (“info.dat”, ios::in | ios::out);

66. ofstream file;
file.open (“info.dat”, ios::in);
if (file)
{
cout }

Should not specify ios::in with an ofstream object. Also, the if statement should read: if (!file)

67. fstream file (“info.dat”);
if (!file)
{
cout }

File access flags must be specified with fstream objects.

68. fstream dataFile (“info.dat”, ios::in | ios::binary);
int x;
datafile

The file access flags should be ios::in and ios::binary.

69. fstream dataFile (“info.dat”, ios:in);
char stuff [81];
dataFile.get (stuff);

The file access flags should be ios::in. Also, the get member function cannot be used to read a string.

70. fstream dataFile (“info.dat”, ios:in);
char stuff [81] = “abcdefghijklmnopqrstuvwxyz”;
dataFile.put (stuff);

The file access flag should be ios::in. Also, the put member function cannot be used to write a string.

71. fstream dataFile (“info.dat”, ios::out);
struct Date
{
int month;
int day;
int year;
};
Date dt = { 4, 2, 98 };
dataFile.write (&dt, sizeof (int));

The file access flag should be ios::out. Also, the last line should read: dataFile.write (reinterpret_cast (&dt), sizeof (dt));

72. fstream inFile (“info.dat”, ios::in);
int x;
inFile.seekp (5);
inFile >> x;

The file access flag should be ios::in. Also, the seekp member function should not be used since the file is opened for input.

Chapter 13

1. What is the difference between a class and an instance of the class?
A class describe a data type. An instance of a class is an object of data type that exists in memory.

2. What is the difference between the following Person structure and Person class.

struct Person
{
string name;
int age;
};

class Person
{
string name;
int age;
};

All members of a struct are public by default. The members of a class, however, are private by default.

3. What is the default access specification of class members?
private

4. Look at the following function header for a member function.

void Circle::getRadius()

What is the name of the function?
The function’s name is getRadius.

What class is the function a member of?
It is a member of the Circle class.

5. A contractor uses a blueprint to build a set of identical houses. Are classes analogous to the blueprint or the houses?
A class is analogous to the blueprint.

6. What is a mutator function? What is an accessor function?
A mutator is a member function that stores a value in a private member variable, or in some way changes an attribute. An accessor is a member function that retrieves the value stored in a private member variable.

7. Is it a good idea to make member variables private? Why or why not?
Yes it is. This protects the variables from being directly manipulated by code outside the class, and prevents them from receiving invalid data.

8. Can you think of a good reason to avoid writing statements in a class member function that use cout or cin?
Unless a class is specifically designed to perform I/O, operations like user input and output are best left to the person designing the application. Classes should provide member functions for retrieving any important data without displaying them on the screen. Likewise, they should provide member functions that store data into private member variables without using cin. This allows a programmer to use the class without being locked into a particular method of performing I/O.

9. Under what circumstances should a member function be private?
When the function is necessary for internal processing, but not useful to the program outside the class. In some cases a class may contain member functions that initialize member variables or destroy their contents. Those functions should not be accessible by an external part of program because they may be called at the wrong time.

10. What is a constructor? What is a destructor?
A constructor is a member function that is automatically called when a class object is created. A destructor is a member function that is automatically called when a class object is destroyed.

11. What is a default constructor? Is it possible to have more than one default constructor?
A default constructor is a constructor that is called without any arguments. It is not possible to have more than one constructor.

12. Is it possible to have more than one constructor? Is it possible to have more than one destructor?
Yes, it is possible to have more than one constructor. It is not possible to have more than one destructor.

13. If a class object is dynamically allocated in memory, does its constructor execute? If so, when?
Yes, the constructor executes when the object is created.

14. When defining an array of class objects, how do you pass arguments to the constructor for each object in the array?
You specify the arguments for each object individually in an initialization list.

15. What are a class’s responsibilities?
A class’s responsibilities are the things that the class is responsible for knowing and the actions that the class is responsible for doing.

16. How do you identify the classes in a problem domain description?
Identify all the nouns (including pronouns and noun phrases) in the problem domain description. Each of these is a potential class. Then, refine the list to include only the classes that are relevant to the problem.

17. The two common programming methods in practice today are ____ and ____
Procedural programming, object-oriented programming

18. ____ programming is centered around functions or procedures.
Procedural

19. ____ programming is centered around objects.
Object-oriented

20. ____ is an object’s ability to contain and manipulate its own data.
Encapsulation

21. In C++ the ____ is the construct primarily used to create objects.
class

22. A class is very similar to a(n) ____
Structure

23. A(n) ____ is a key word inside a class declaration that establishes a member’s accessibility.
Access specifier

24. The default access specification of class members is ____
private

25. The default access specification of a struct in C++ is ____
public

26. Defining a class object is often called the ____ of a class.
Instantiation

27. Members of a class object may be accessed through a pointer to the object by using the ____ operator.
->

28. If you were writing the declaration of a class named Canine, what would you name the file it was stored in? ____
canine.h

29. If you were writing the external definitions ofthe Canine class’s member functions, you would save them in a file named ____
canine.cpp

30. When a member function’s body is written inside a class declaration, the function is ____
inline

31. A(n) ____ is automatically called when an object is created.
Constructor

32. A(n) ____ is a member function with the same name as the class.
Constructor

33. ____ are useful for performing initialization or setup routines in a class object.
Constructors

34. Constructors cannot have a(n) ____ type.
Return

35. A(n) ____ constructor is one that requires no arguments.
Default

36. A(n) ____ is a member function that is automatically called when an object is destroyed.
Destructor

37. A destructor has the same name as the class, but is preceded by a(n) ____ character.
~

38. Like constructors, destructors cannot have a(n) ____ type.
Return

39. A constructor whose arguments all have default values is a(n) ____ constructor.
Default

40. A class may have than one constructor, as long as each has a different ____
Parameter list

41. A class may only have one default ____ and one ____
Constructor, destructor

42. A(n) ____ may be used to pass arguments to the constructors of elements in an object array.
Initialization list

43. Write a class declaration named Circle with a private member variable named radius. Write set and get functions to access the radius variable, and a function named getArea that returns the area of the circle. The area is calculated as: 3.14159 * radius * radius

class Circle
{
private;
double radius;
public;
void setRadius (double r)
{ radius = r; }
double getRadius()
{ return radius; }
double getArea()
{ return 3.14159 * radius * radius; }
};

44. Add a default constructor to the Circle class in question 43. The constructor should initialize the radius member to 0.

class Circle
{
private:
double radius;
public:
Circle()
{ radius = 0.0; }
void setRadius (double r)
{ radius = r; }
double getRadius()
{ return radius; }
double getArea()
{ return 3.14159 * radius * radius; }
};

45. Add an overloaded constructor to the Circle class in question 44. The constructor should accept an argument an assign its value to the radius member variable.

class Circle
{
private:
double radius;
public:
Circle()
{ radius = 0.0; }
Circle (double r)
{ radius = 0.0; }
void setRadius (double r)
{ radius = r; }
double getRadius()
{ return radius; }
double getArea()
{return 3.14159 * radius * radius; }
};

46. Write a statement that defines an array of five objects of the Circle class in question 45. Let the default constructor execute for each element of the array.

const int SIZE = 5;
Circle collection [SIZE];

47. Write a statement that defines an array of five objects of the Circle class in question 45. Pass the following arguments to the elements’ constructor: 12, 7, 9, 14, and 8.

const int SIZE = 25;
Circle collection [SIZE] = {12, 7, 9, 14, 8 };

48. Write a for loop that displays the radius and area o the circles represented by the array you defined in question 47.

for (int i = 0; i {
cout cout cout cout }

49. If the items on the following list appeared in a problem domain description, which would be potential classes?

AnimalMedicationNurse

InoculateOperateAdvertise

DoctorInvoiceMeasure

PatientClientCustomer

The ones that would be potential classes are:

AnimalMedicationNurse

DoctorInvoiceCustomer

PatientClient

50. Look at the following description of a problem domain:

The bank offers the following types of accounts to its customers: savings accounts, checking accounts, and money market accounts. Customers are allowed to deposit money into an account (thereby increasing its balance), withdraw money from an account (thereby decreasing its balance), and earn interest on the account. Each account has an interest rate.

Assume that you are writing an application that will calculate the amount of interest earned for a bank account.

A) Identify the potential classes in this problem domain.
B) Refine the list to include only the necessary class or classes for this problem.
C) Identify the responsibilities of the class or classes.

A) After eliminating duplicates, objects, and primitive values, the potential classes are: bank, account, and customer
B) The only class needed for this particular problem is account.
C) The account class knows its balance and interest rate.
The account can calculate interest earned.

51. Private members must be declared before public members.
False

52. Class members are private by default.
True

53. Members of a struct are private by default.
False

54. Classes and structures in C++ are very similar.
True

55. All private members of a class must be declared together.
False

56. All public members of a class must be declared together.
False

57. It is legal to define a pointer to a class object.
True

58. You can use the new operator to dynamically allocate an instance of a class.
True

59. A private member function may be called from a statement outside the class, as long as the statement is in the same program as the class declaration.
False

60. Constructors do not have to have the same name as the class.
False

61. Constructors may not have a return type.
True

62. Constructors cannot take arguments.
False

63. Destructors cannot take arguments.
True

64. Destructors may return a value.
False

65. Constructors may have default arguments.
True

66. Member functions may be overloaded.
True

67. Constructors may not be overloaded.
False

68. A class may not have a constructor with no parameter list, and a constructor whose arguments all have default values.
True

69. A class may only have one destructor.
True

70. When an array of objects is defined, the constructor is only called for the first element.
False

71. To find the classes needed for an object-oriented application, you identify all of the verbs in a description of the problem domain.
False

72. A class’s responsibilities are the things the class is responsible for knowing, and actions the class must perform.
True

73. class Circle;
{
private
double centerX;
double centerY;
double radius;
public
setCenter (double, double);
setRadius (double);
}

There should not be a colon after the word Circle.
Colons should appear after the words private and public.
A semicolon should appear after the closing brace.

74. #include using namespace std;

Class Moon;
{
Private
double earthWeight;
double moonWeight;
Public
moonWeight (double ew);
{ earthWeight = ew; moonWeight = earthWeight / 6; }
double getMoonWeight();
{ return moonWeight; }
}
int main()
{
double earth;
cout >> “What is your weight? “;
cin Moon lunar (earth);
cout cout return 0;
}

The semicolon should not appear after the word Moon.
The first character of the words private and public should not be capitalized.
There should be a colon, not a semicolon, following the words private and public.
Semicolons should not appear in the member function headers.
In function main an argument is passed to a constructor that does not exist in the Moon class.
The moonWeight member function should have been called prior to getMoonWeight.

75. #include
using namespace std;

class DumbBell;
{
int weight;
public:
void setWeight (int);
};
void setWeight (int w)
{
weight = w;
}
int main()
{
DumbBell bar;

DumbBell (200);
cout return 0;
}

The semicolon should not appear after the word DumbBell.
The function header for setWeight should appear as:
void DumbBell::setWeight (int w)
The line that reads:
DumbBell (200);
should read:
bar.setWeight (200);

bar.weight cannot be accessed outside of the class because no access specifier appeared before it in the class, making the variable private to the class by default.
This means the cout statement will not work.

76. class Change
{
public:
int pennies;
int nickels;
int dimes;
int quarters;
Change()
{ pennies = nickels = dimes = quarters = 0; }
Change (int p = 100, int n = 50, d = 50, q =25);
};

void Change::Change (int p, int n, d, q)
{
pennies = p;
nickels = n;
dimes = d;
quarters = q;
}

Both constructors are considered the default constructor.

Short Answer Question

Compare text file with binary file.
Binary file is a more secured file. Binary file uses less data storage for the same amount of data to be stored.