1 / 45

Chapter 15

Chapter 15. Objectives. You should be able to describe: I/O File Stream Objects and Methods Reading and Writing Character-Based Files Exceptions and File Checking Random File Access File Streams as Function Arguments Common Programming Errors. I/O File Stream Objects and Methods.

sierra-king
Télécharger la présentation

Chapter 15

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Chapter 15

  2. Objectives You should be able to describe: • I/O File Stream Objects and Methods • Reading and Writing Character-Based Files • Exceptions and File Checking • Random File Access • File Streams as Function Arguments • Common Programming Errors

  3. I/O File Stream Objects and Methods • File: Collection of data that is stored together under common name, usually on disk, magnetic tape, or CD • C++ programs stored on disk are examples of files • The stored data in program file is program code that becomes input data to C++ compiler • A C++ program is not usually considered data, and term file, or data file, is typically used to refer only to external files that contain the data used in C++ program

  4. I/O File Stream Objects and Methods (continued) • External name: Unique file name for file • External name is how operating system knows file • Contents of directory or folder are listed by external names • Format of external names: Each computer operating system has its own specifications for external file size • Table 15.1 lists specifications for more commonly used operating systems

  5. I/O File Stream Objects and Methods (continued)

  6. I/O File Stream Objects and Methods (continued) • File naming conventions: • Use descriptive names • Avoid long file names • They take more time to type and can result in typing errors • Manageable length for file name is 12 to 14 characters, with maximum of 25 characters • Choose file names that indicate type of data in file and application for which it is used • Frequently, first eight characters describe data, and an extension describes application

  7. I/O File Stream Objects and Methods (continued) • More file naming conventions • Using DOS convention, the following are all valid computer data file names: prices.dat records info.txt exper1.dat scores.dat math.mem

  8. File Stream Objects • File stream: One-way transmission path that is used to connect file stored on physical device, such as disk or CD, to program • Mode (of file stream): Determines whether path will move data from file into program or from program to file • Input file stream: Receives or reads data from file into program • Output file stream: Sends or writes data to file

  9. File Stream Objects (continued) • Direction (mode) of file stream is defined in relation to program and not file: • Data that goes into program are considered input data • Data sent out from program are considered output data • Figure 15.1 illustrates data flow from and to file using input and output streams

  10. File Stream Objects (continued)

  11. File Stream Objects (continued) • Distinct file stream object must be created for each file used, regardless of file’s type • For program to both read and write to file, both an input and output file stream object are required • Input file stream objects are declared to be of type ifstream • Output file streams are declared to be of type ofstream

  12. File Stream Objects (continued) • Two basic types of files: both store data using binary code • Text (character-based) files: Store each character using individual character code (typically ASCII or Unicode) • Advantage: Allows files to be displayed by word processing program or text editor • Binary-based files: Store numbers in binary form and strings in ASCII or Unicode form • Advantage: Provides compactness

  13. File Stream Methods • Each file stream object has access to methods defined for its respective ifstream or ofstream class, including: • Opening file: connecting stream object name to external file name • Determining whether a successful connection has been made • Closing file: closing connection • Getting next data item into program from input stream • Putting new data item from program onto output stream • Detecting when end of file has been reached

  14. File Stream Methods (continued) • open() method: • Establishes physical connecting link between program and file • Operating system function that is transparent to programmer • Connects file’s external computer name to stream object name used internally by program • Before a file can be opened, it must be declared as either ifstream or ofstream object • File opened for input is said to be in read mode

  15. File Stream Methods (continued) • Example:inFile.open("prices.dat"); • connects external text file named prices.dat to internal program file stream object named inFile • Accesses file using internal object name inFile • Computer saves file under the external name prices.dat • Calling the open() method uses the standard object notation: objectName.open()

  16. File Stream Methods (continued) • fail() method: returns true value if file is unsuccessfully opened, false if open succeeded • Good programming practice is to check that connection is established before using file • In addition to fail() method, C++ provides three other methods, listed in Table 15.2, that can be used to detect file’s status • Program 15.1 illustrates statements required to open file for input including error checking routine to ensure that successful open was obtained

  17. File Stream Methods (continued) • Example of use of fail() method: ifstream inFile; // any object name can be used here inFile.open("prices.dat"); // open the file // check that the connection was successfully // opened if (inFile.fail()) { cout << "\nThe file was not successfully opened" << "\n Please check that the file currently exists." << endl; exit(1); }

  18. File Stream Methods (continued)

  19. File Stream Methods (continued)

  20. File Stream Methods (continued)

  21. File Stream Methods (continued) • Different checking required for output files • If file exists having same name as file to be opened in output mode, existing file is erased and all data lost • To avoid this situation, file is first opened in input mode to see if it exists • If it does, user is given choice of explicitly permitting it to be overwritten (when it is later opened in output mode) • Code used to accomplish this is highlighted in Program 15.2

  22. Embedded and Interactive File Names • Embedding a file name in program causes problems • No provision for user to enter desired file name during program execution • Any changes require modification of open() method and recompile • These problems can be solved by assigning file name to string variable as shown in Programs 15.3a and 15.3b • String variable: Variable that can hold string value

  23. Embedded and Interactive File Names (continued)

  24. Embedded and Interactive File Names (continued)

  25. Closing a File • close() method: Breaks connection between file’s external name and file stream object • Object can then be used for another file • Good programming practice is to close files no longer needed • Operating system automatically closes any open files at end of normal program execution • Example: The statement inFile.close(); closes inFile stream’s connection to its current file • close() method takes no argument

  26. Reading and Writing Character-Based Files • Operations similar to reading input from keyboard and writing data to display screen • For writing to file, the cout object is replaced by ofstream object name declared in program • Example: If outFile is declared as object of type ofstream, the following output statement is valid: outFile << descrip << ' ' << price; • The file name directs output stream to file instead of standard display device • Example: Program 15.4

  27. Reading and Writing Character-Based Files (continued) • Program 15.4 output: • File named prices.dat is created and saved by computer as text file (the default file type) • prices.dat is sequential file consisting of the following data: Mats 39.95 Bulbs 3.22 Fuses 1.08 • Actual storage of characters in file depends on character codes used by computer • Output file file contains 36 characters (Figure 15.2)

  28. Reading and Writing Character-Based Files (continued)

  29. Reading from a Text File • Almost identical to reading data from standard keyboard • cin object replaced by ifstream object declared in program • Example: The input statement inFile >> descrip >> price; reads next two items in file and stores them in variables descrip and price • File stream name directs input to come from file stream rather than standard input device stream

  30. Reading from a Text File (continued) • Program 15.5 illustrates how the prices.dat file created in Program 15.4 can be read • Also illustrates method of detecting end-of-file (EOF) marker using good() function (see Table 15.2) • Other methods that can be used for stream input are listed in Table 15.3 • Each method must be preceded by stream object name

  31. Reading from a Text File (continued)

  32. Standard Device Files • C++ supports logical and physical file objects • Logical file object: Stream that connects file of logically related data (data file) to a program • Physical file object: Stream that connects to hardware device such as keyboard or printer • Standard input file: Physical device assigned to program for data entry • Standard output file: Physical device on which output is automatically displayed

  33. Other Devices • The keyboard, display, error reporting, and logging streams are automatically connected to the stream objects named cin, cout, cerr, clog • Requires iostream header file • Other devices can be used if the name assigned by system is known • Example: Most personal computers assign name prn to printer connected to computer • Statement outFile.open("prn") connects printer to ofstream object named outFile

  34. Exceptions and File Checking • Error detection and exception handling are used in C++ programs that access one or more files • General exception handling code (section 7.3) try { // one or more statements, at least one // of which should throw an exception } catch(exceptionDataType parameterName) { // one or more statements } • Program 15.7 illustrates file opening exception handling

  35. Opening Multiple Files • Example: Read the data from character-based file named info.txt, one character at a time, and write this data to file named backup.txt • Essentially, this is a file-copy program • Figure 15.4 illustrates structure of streams needed to produce file copy • Program 15.9 creates backup.txt file as an exact duplicate of info.txt file using procedure described in Figure 15.4

  36. Opening Multiple Files (continued)

  37. Random File Access • File access: Retrieving data from file • File organization: The way data is stored in a file • Sequential organization: Characters in file are stored in sequential manner, one after another • Random Access: Any character in an open file can be read directly without having to read characters ahead of it

  38. Random File Access (continued) • File position marker: Long integer that represents an offset from the beginning of each file • Keeps track of where next character is to be read from or written to • Allows for random access of any individual character • Table 15.4 shows functions used to access and change the file position marker • Program 15.10 illustrates use of seek() and tell() to read and display file in reverse order

  39. Random File Access (continued)

  40. File Streams as Function Arguments • A file stream object can be used as function argument • Function’s formal parameter must be a reference (see Section 6.3) to appropriate stream, either as ifstream& or ofstream& • Example: Program 15.11 • ofstream object named outfile is opened in main() • Stream object is passed to the function inOut() • inOut() is used to write five lines of user-entered text to file

  41. Common Programming Errors • Using file’s external name in place of internal file stream object name when accessing file • Opening file for output without first checking that file with given name already exists • Not checking for preexisting file ensures that file will be overwritten • Not understanding that end of a file is detected only after EOF sentinel has either been read or passed over

  42. Common Programming Errors (continued) • Attempting to detect end of file using character variables for EOF marker • Any variable used to accept EOF must be declared as an integer variable • Using integer argument with the seekg() and seekp() functions • Offset must be a long integer constant or variable • Any other value passed to these functions can result in unpredictable result

  43. Summary • A data file is any collection of data stored in an external storage medium under a common name • A data file is connected to file stream using fstream’s open() method • This function connects file’s external name with internal object name • A file can be opened in input or output mode • An opened output file stream either creates a new data file or erases data in an existing opened file

  44. Summary (continued) • All file streams must be declared as objects of either the ifstream or ofstream classes • In addition to any files opened within a function, the standard stream objects cin, cout, and cerrare automatically declared and opened when a program is run

  45. Summary (continued) • Data files can be accessed randomly using the seekg(),seekp(), tellg(), and tellp() methods • The g versions of these functions are used to alter and query file position marker for input file streams • The p versions do the same for output file streams • Table 15.5 lists the methods supplied by the fstream class for file manipulation

More Related