Previous Page TOC Next Page



- Project 12 -
Using Disk Files


In this lesson, you learned about libraries of functions and classes, and you saw how to use disks. You have been using files throughout the book to use the screen and the keyboard, but you learned more about the extra techniques for disks. In this lesson, you saw the following:

Project 12 Listing. Using files.


  1:// File name: PROJCT12.CPP

  2:// A simple file maintenance program which

  3:// can add or update entries

  4://

  5:#include <fstream.h>

  6:#include <ctype.h>

  7:

  8:struct PhoneList

  9:  {

 10:    char name[31];

 11:    char phone[21];

 12:  };

 13:

 14:// Function prototypes

 15:void Add(fstream& phone);

 16:void Update(fstream& phone);

 17:void List(fstream& phone);

 18:

 19:void main()

 20:  {

 21:    char answer = ' ';

 22:    // Declare the stream

 23:    fstream phone("phone.lst",ios::in | ios::out);

 24:

 25:    if (!phone) // If phone file has not been opened

 26:      {

 27:        cout << "*** Error opening file phone.lst ***";

 28:        return;

 29:      }

 30:

 31:    while (1) // Do forever

 32:      {

 33:        cout << endl << "dd, (U)pdate, (L)ist, (Q)uit? ";

 34:        cin >> answer;

 35:        cin.ignore(80,'\n');

 36:        cout << endl;

 37:

 38:        switch (toupper(answer)) // Allow single test

 39:          {

 40:            case 'A':

 41:              Add(phone);

 42:              break;

 43:            case 'U':

 44:              Update(phone);

 45:              break;

 46:            case 'L':

 47:              List(phone);

 48:              break;

 49:            case 'Q':

 50:              return;

 51:          }

 52:      }

 53:    }

 54://-------------------------------------------------------------

 55:// Add a phone entry

 56://

 57:void Add(fstream& phone)

 58:  {

 59:    PhoneList entry = {0};

 60:

 61:    cout << "What is the name? ";

 62:    cin.getline(entry.name,31);

 63:    cout << "What is the number? ";

 64:    cin.getline(entry.phone,21);

 65:

 66:    phone.seekg(0,ios::end); // Move to end of file

 67:    phone.write((char*)&entry,sizeof(PhoneList));

 68:  }

 69://-------------------------------------------------------------

 70:// Update a phone entry

 71://

 72:

 73:void Update(fstream& phone)

 74:  {

 75:    PhoneList entry = {0};

 76:    const int size = sizeof(PhoneList);

 77:    int count = 0;

 78:

 79:    cout << "Enter entry number :" ;

 80:    cin >> count;

 81:    cin.ignore(80,'\n');

 82:    if (count < 1)

 83:      {

 84:        cout << "Error - not a valid entry" << endl;

 85:        return;

 86:      }

 87:

 88:    // Find record

 89:    phone.seekg(size*(count - 1),ios::beg); // Find it

 90:    phone.read((char*)&entry,size);         // Read it

 91:    if (phone.bad() || phone.eof())         // Check for error

 92:      {

 93:        cout << "Error - not a valid entry" << endl;

 94:        phone.clear();               // Clear error flags

 95:        return;

 96:      }

 97:

 98:    cout <<  count  << ": "         // Confirm entry

 99:            << entry.name << '\t'

100:            << entry.phone << endl;

101:    cout << "New name (blank for cancel)? ";

102:    cin.getline(entry.name,31);

103:    if (entry.name[0] == '\0') // Quick zero length test

104:      return;

105:    cout << "New number? ";

106:    cin.getline(entry.phone,21);

107:

108:    phone.seekg(size*(count - 1),ios::beg); // Find it again

109:    phone.write((char*)&entry,size);        // Write it

110:  }

111:

112:void List (fstream& phone)

113:  {

114:    PhoneList entry;

115:    int count = 0;

116:

117:    cout << "Name\tNumber" << endl;

118:    phone.seekg(0,ios::beg); // Set position to beginning

119:    while (!phone.eof())     // While more entries

120:     {

121:       phone.read((char*)&entry,sizeof(PhoneList));

122:       if (phone.eof())      // Eof not set till after end

123:         break;

124:       cout << ++count << ": "

125:            << entry.name << '\t'

126:            << entry.phone << endl;

127:     }

128:    phone.clear();           // Reset eof flag

129:  }

OUTPUT


dd, (U)pdate, (L)ist, (Q)uit? L

Name    Number

1: CompuServe   0121 359 4000

2: Directory Enquiries  192

dd, (U)pdate, (L)ist, (Q)uit? A

What is the name? Operator

What is the number? 100

dd, (U)pdate, (L)ist, (Q)uit? U

Enter entry number :2

2: Directory Enquiries  192

New name (blank for cancel)? International Enquiries

New number? 153

dd, (U)pdate, (L)ist, (Q)uit? L

Name    Number

1: CompuServe   0121 359 4000

2: International Enquiries      153

3: Operator     100

dd, (U)pdate, (L)ist, (Q)uit? q

Second run:


dd, (U)pdate, (L)ist, (Q)uit? L

Name    Number

1: CompuServe   0121 359 4000

2: International Enquiries      153

3: Operator     100

dd, (U)pdate, (L)ist, (Q)uit? q

Description

1: Some comments to describe the program.

2: The comments continue.

3: The comments continue.

4: Empty comments can enhance the appearance of your program.

5: Include the file stream header.

6: Include header for toupper.

7: Blank lines help to make your program more readable.

8: Declare a structure called PhoneList.

9: Structure declarations start with an opening brace.

10: Declare a member to hold the name.

11: Declare a member to hold the number.

12: All structure declarations end with a closing brace and semicolon.

13: Blank lines help to make your program more readable.

14: A comment to describe the workings of the code.

15: Prototype for global function Add().

16: Prototype for global function Update().

17: Prototype for global function List().

18: Blank lines help to make your program more readable.

19: Declare the main() routine.

20: All functions start with an opening brace.

21: Declare a variable for receiving the keyboard input.

22: A comment to describe the workings of the code.

23: Declare an fstream object to open file PHONE.LST in the current working directory.

24: Blank lines help to make your program more readable.

25: If there is a problem with the file. . .

26: An opening brace marks the start of statements within the if block.

27: Give an error message to the user.

28: Exit the program.

29: A closing brace marks the end of statements within the if block.

30: Blank lines help to make your program more readable.

31: Perform the following statements until a break or return is encountered.

32: An opening brace marks the start of statements to be repeated.

33: Prompt the user for input.

34: Get the first character that is typed.

35: Ignore any following characters, including the end of line.

36: Output a blank line to neaten the output.

37: Blank lines help to make your program more readable.

38: Decide which option the user asked for.

39: switch statements start with an opening brace.

40: If the user chose add. . .

41: Call the Add() function.

42: Continue processing after the switch statement.

43: If the user chose update. . .

44: Call the Update() function.

45: Continue processing after the switch statement.

46: If the user chose list. . .

47: Call the List() function.

48: Continue processing after the switch statement.

49: If the user chose to quit. . .

50: return in main() ends the program.

51: This brace ends the switch statement.

52: This brace ends the while loop.

53: This brace ends the main() function.

54: A comment highlights the start of a function definition.

55: A comment to note what the function is for.

56: Empty comments can enhance the appearance of your code.

57: Define a function to add an entry to the phone list.

58: All functions start with an opening brace.

59: Declare a PhoneList structure and initialize it to all zeros.

60: Blank lines help to make your program more readable.

61: Ask the user for input.

62: Get a line of input.

63: Ask the user for input.

64: Get a line of input.

65: Ask the user for input.

62: Get a line of input.

63: Ask the user for input.

64: Get a line of input.

65: Blank lines help to make your program more readable.

66: Move to the end of the file.

67: Write out the structure to the end of the file.

68: A function always ends with a closing brace.

69: A comment can be used to help find a function definition.

70: A comment to describe the function.

71: Blank comments can enhance the appearance of your code.

72: Blank lines help to make your program more readable.

73: A function to update the file is defined.

74: All functions start with an opening brace.

75: Declare a PhoneList structure and initialize it to all zeros.

76: A constant is declared to make the code more readable.

77: Declare a variable to record the record number.

78: Blank lines help to make your program more readable.

79: Prompt the user for input.

80: Get the user's response.

81: Ignore any extra characters.

82: If the input is invalid, reject it.

83: A brace marks the start of the if block.

84: Send an error message to the user.

85: Exit the function.

86: A brace marks the end of the if block.

87: Blank lines help to make your program more readable.

88: A comment to describe the workings of the code.

89: Find the record by calculating the record length multiplied by the record number.

90: Read the record.

91: If there is a problem reading the record (such as it is off the end of file). . .

92: A brace starts the if block.

93: Send an error message to the user.

94: Clear the file error flags.

95: Return to the calling function.

96: The brace marks the end of an if statement.

97: Blank lines help to make your program more readable.

98: Inform the user of the current data.

99: Continue the message.

100: Continue the message.

101: Prompt the user for new data.

102: Get the new name.

103: If the user picked the wrong record, allow the update to be canceled.

104: Leave the update routine.

105: Ask for the new phone number.

106: Get the new phone number.

107: Blank lines help to make your program more readable.

108: After the read, the file pointer will have moved; reset it.

109: Write out the data on top of old data.

110: All functions end with a closing brace.

111: Blank lines help to make your program more readable.

112: Define a function to list the entries on the file.

113: All functions start with an opening brace.

114: Declare a PhoneList structure variable.

115: Initialize a count.

116: Blank lines help to make your program more readable.

117: Output a title.

118: Set the file pointer to the start of file.

119: While the end of file is not reported, continue the following processing.

120: The statements repeated are enclosed in braces.

121: Read the file at the current position.

122: If read causes end of file to occur, no more records exist.

123: Leave the while loop.

124: Output the record count.

125: Continue the output with the name.

126: Continue the output with the phone number.

127: The brace marks the end of the while loop.

128: Reset any file flags that might have been set.

129: All functions end with a closing brace.



5: This header also includes cout and cin, so IOSTREAM.H is not required.

38: toupper makes the lowercase input into uppercase input, saving case statement entries.

57: Objects can be passed as parameters. This needs a reference to avoid creating a copy of the file object.

103: It is good practice to allow users to change their minds after they have had feedback on their choice.

121: read moves the file pointer to after the last character read.


Previous Page Page Top TOC Next Page