Chapter 9 : I/O Streams and Data Files (pp )

Size: px
Start display at page:

Download "Chapter 9 : I/O Streams and Data Files (pp )"

Transcription

1 Page 1 of 34 Printer Friendly Version User Name: Stephen Castleberry Id: scastleberry@rivercityscience.org Book: A First Book of C Cengage Learning Inc. All rights reserved. No part of this work may by reproduced or used in any form or by any means - graphic, electronic, or mechanical, or in any other manner - without the written permission of the copyright holder. Chapter 9 : I/O Streams and Data Files (pp ) I/O Streams and Data Files: Chapter Objectives 9.1 I/O File Stream Objects and Methods 9.2 Reading and Writing Text Files 9.3 Random File Access 9.4 File Streams as Function Arguments 9.5 Common Programming Errors 9.6 Chapter Summary 9.7 Chapter Supplement: The iostream Class Library I/O Streams and Data Files: Chapter Overview The data for the programs you have used so far has been assigned internally in the programs or entered by the user during program execution. Therefore, the data used in these programs is stored in the computer's main memory and ceases to exist after the program using it has finished executing. This type of data entry is fine for small amounts of data. However, imagine a company having to pay someone to type in the names and addresses of hundreds or thousands of customers every month when bills are prepared and sent. As you learn in this chapter, storing large amounts of data outside a program on a convenient storage medium is more sensible. Data stored together under a common name on a storage medium other than the computer's main memory is called a data file. Typically, data files are stored on disks, USB drives, or CD/DVDs. Besides providing permanent storage for data, data files can be shared between programs, so the data one program outputs can be input in another program. In this chapter, you learn how data files are created and maintained in C++. P. 387

2 Page 2 of I/O File Stream Objects and Methods To store and retrieve data outside a C++ program, you need two things: Files A file A file stream object A file is a collection of data stored together under a common name, usually on a disk, USB drive, or CD/DVD. For example, the C++ programs you store on disk are examples of files. The stored data in a program file is the code that becomes input data to the C++ compiler. In the context of data processing, however, stored programs aren't usually considered data files; the term data file typically refers only to files containing the data used in a C++ program. Each stored data file has a unique filename, referred to as the file's external name. The external name is how the operating system (OS) knows the file. When you review the contents of a directory or folder (for example, in Windows Explorer), you see files listed by their external names. Each computer OS has its own specification for the maximum number of characters permitted for an external filename. Table 9.1 lists these specifications for common current and past OSs. Table 9.1 Maximum Allowable Filename Characters OS Maximum Filename Length DOS 8 characters plus an optional period and 3-character extension Windows 98, 2000, XP, Vista 255 characters Windows characters UNIX Early versions 14 characters Current versions 255 characters Table 9.1 Maximum Allowable Filename Characters For current OSs, you should take advantage of the increased length specification to create descriptive filenames, but avoid using extremely long filenames because they take more time to type and can result in typing errors. A manageable length for a filename is 12 to 14 characters, with a maximum of 25 characters. For all the OSs listed in Table 9.1, the following are valid data filenames: Choose filenames that indicate the type of data in the file and the application for which it's used. Typically, the first 8 to 10 characters describe the data, and an optional extension (a period and three or four characters) describes the application used to create the file. For example, P. 388 Point of Information: Functions and Methods C++ programmers can make full use of the many functions C++ classes provide without knowing the internal details of how the function is constructed or even how to construct a class. Functions provided as part of a class are formally referred to as class methods (or methods, for short). Although a method is often referred to as a function, the term method tells you it's not just a stand-alone function, as discussed in Chapter 6, but is available as part of a class. Typically, a class contains other methods of a similar type. More important, almost all class methods are invoked in a different manner from functions. Chapters 10 and 11 in Part II explain classes and their construction in detail. As you'll see, a class is constructed from C++ code that includes both data and methods. Excel adds the.xls or.xlsx extension automatically to all spreadsheet files (x refers to the version number), Microsoft Word stores files with the extension.doc or.docx, and C++ compilers require a program file with the extension.cpp. When creating your own filenames, you should adhere to this practice of using descriptive filenames. For example, the name exper1.dat is suitable for describing a file of data corresponding to experiment number 1. Two basic types of files exist: text files, also known as character-based files, and binary-based files. Both file types store data by using a binary code; the difference is in what the codes represent. Briefly, text files store each character, such as a letter, digit, dollar sign, decimal point, and so on, by using a character code (typically ASCII or Unicode). With a character code, a wordprocessing

3 Page 3 of 34 program or text editor can read and display these files. Additionally, because text files are easy to create, most programmers use them more often. Text files are the default file type in C++ and the file type discussed in this chapter. Binary-based files use the same code the C++ compiler uses for primitive data types. This means numbers appear in their true binary form and can't be read by word-processing programs and text editors. The advantage of binary-based files is compactness; storing numbers with their binary code usually takes less space than with character values. File Stream Objects A file stream is a one-way transmission path used to connect a file to a program. Each file stream has its own mode that determines the direction of data on the transmission path that is, whether the path moves data from a file to a program or from a program to a file. A file stream used to transfer data from a file to a program is an input file stream. A file stream that sends data from a program to a file is an output file stream. The direction, or mode, is defined in relation to the program, not the file; data going into a program is considered input data, and data sent out from a program is considered output data. Figure 9.1 illustrates the data flow from and to a file, using input and output file streams. P. 389 output file streams Figure 9.1 Input and For each file your program uses, regardless of the file's type (text or binary), a distinct file stream object must be created. If you want your program to read from and write to a file, both input and output file stream objects are required. Input file stream objects are declared to be of type ifstream, and output file stream objects are declared to be of type ofstream. For example, the following declaration statement declares an input file stream object named infile to be an object of the ifstream class: Similarly, the following declaration statement declares an output file stream object named outfile to be an object of the ofstream class: In a C++ program, a file stream is accessed by its stream object name: one name for reading the file and one name for writing to the file. Object names, such as infile and outfile, can be any programmer-selected name that conforms to C++'s identifier rules. File Stream Methods Each file stream object has access to the methods defined for its ifstream or ofstream class. These methods include connecting a stream object name to an external filename (called opening a file), determining whether a successful connection has been made, closing a connection (called closing a file), getting the next data item into the program from an input stream, putting a new data item from the program onto an output stream, and detecting when the end of a file has been reached. Opening a file connects a file stream object to a specific external filename by using a file stream's open() method, which accomplishes two purposes. First, opening a file establishes the physical connecting link between a program and a file. Because details of this link are handled by the computer's OS, not by the program, normally the programmer doesn't need to consider them. From a coding perspective, the second purpose of opening a file is more relevant. Besides establishing the actual physical connection between a program and a data file, opening a file connects the file's external OS name to the file stream object name the program uses internally. The method that performs this task, open(), is provided by the ifstream and ofstream classes. P. 390

4 Page 4 of 34 Point of Information: Input and Output Streams A stream is a one-way transmission path between a source and a destination. In data transmission, a stream of bytes is sent down this transmission path, similar to a stream of water providing a one-way path for water to travel from a source to a destination. Stream objects are created from stream classes. You have already used two stream objects extensively: the input stream object named cin and the output stream object named cout. The cin object, created from the istream class, provides a transmission path from keyboard to program, and the cout object, created from the ostream class, provides a transmission path from program to screen. The istream and ostream classes are used to construct a class named iostream. When the iostream header file is included in a program with the #include <iostream> directive, the cin and cout stream objects are declared automatically and opened by the C++ compiler. File stream objects provide the same capabilities as the cin and cout objects, except they connect a program to a file rather than the keyboard or screen. File stream objects must be created and declared in a similar manner as variables. Instead of being declared as int or char, however, file stream objects are declared as being of the ifstream class (for input) or of the ofstream class (for output). These two classes are made available by including the fstream header file with the #include <fstream> directive. In using the open() method to connect the file's external name to its internal object stream name, only one argument is required: the external filename. For example, the following statement connects the external text file named prices.dat to the internal file stream object named infile: This statement assumes, of course, that infile has been declared as an ifstream or ofstream object. If a file has been opened with the preceding statement, the program accesses the file by using the internal object name infile, and the OS accesses the file under the external name prices.dat. The external filename argument passed to open() is a string enclosed in double quotation marks. The prices.dat file exists or is created (depending on whether it's designated as an input or output file) in the same folder as the program. More generally, data files are stored in separate folders, and the data file's full pathname can be specified as in this example: Notice that two slashes separate folder names and filenames, which is required when providing a full pathname. Also, in these two examples, the open() method is called by giving the object name (infile) first, followed by a period, and then the method name (open). With a few notable exceptions, this is how all class methods are called. When an existing file is connecting to an input file stream, the file's data is made available for input, starting at the first data item in the file. Similarly, a file connected to an output file stream creates a new file, said to be in output mode, and makes the file available for output. If P. 391 a file exists with the same name as a file opened in output mode, the old file is erased (overwritten) and all its data is lost. When opening a file for input or output, good programming practice requires checking that the connection has been established before attempting to use the file. You can do this with the fail() method, which returns a true value if the file was opened unsuccessfully (that is, it's true the open failed) or a false value if the open succeeded. Typically, the fail() method is used in code similar to the following, which attempts to open the prices.dat file for input, checks that a valid connection was made, and reports an error message if the file wasn't opened for input successfully: If the fail() method returns a true, indicating that the open failed, this code displays an error message. In addition, the exit() function, which is a request to the OS to end program execution immediately, is called. The cstdlib header function must be included in any

5 Page 5 of 34 program using exit(), and exit()'s single-integer argument is passed directly to the OS for any further program action or user inspection. Throughout the remainder of the book, this type of error checking is included whenever a file is opened. (Section 14.4 shows how to use exception handling for the same type of error checking.) In addition to the fail() method, C++ provides three other methods, listed in Table 9.2, for detecting a file's status. Table 9.2 File Status Methods Prototype Description fail() Returns a Boolean true if the file hasn't been opened successfully; otherwise, returns a Boolean false value. eof() Returns a Boolean true if a read has been attempted past the end of file; otherwise, returns a Boolean false. The value becomes true only when the first character after the last valid file character is read. Table 9.2 File Status Methods P. 392 Table 9.2 File Status Methods (continued) Prototype Description good() Returns a Boolean true while the file is available for program use. Returns a Boolean false if a read has been attempted past the end of file. The value becomes false only when the first character after the last valid file character is read. bad() Returns a Boolean true if a read has been attempted past the end of file; otherwise, returns a false. The value becomes true only when the first character after the last valid file character is read. Table 9.2 File Status Methods (continued) Program 9.1 shows the statements required to open a file for input, including an error-checking routine to ensure that the open was successful. A file opened for input is said to be in read mode or input mode. (These two terms are synonymous.) Program 9.1

6 Page 6 of 34 P. 393 A sample run of Program 9.1 produces the following output: A different check is required for output files (files that are written to) because if a file exists with the same name as the file to be opened in output mode, the existing file is erased and all its data is lost. To avoid this situation, the file is first opened in input mode to see whether it exists. If it does, the user is given the choice of permitting it to be overwritten when it's opened later in output mode. The code to perform this check is shaded in Program 9.2. Program 9.2

7 Page 7 of 34 P. 394 The following two runs were made with Program 9.2: and

8 Page 8 of 34 Although Programs 9.1 and 9.2 can be used to open an existing file for reading and writing, both programs lack statements to perform a read or write and close the file. These topics are discussed shortly. Before moving on, however, note that it's possible to combine the declaration of an ifstream or ofstream object and its associated open() statement into one statement. For example, examine these two statements in Program 9.1: They can be combined into a single statement: Embedded and Interactive Filenames Programs 9.1 and 9.2 have two problems: The external filename is embedded in the program code. There's no provision for a user to enter the filename while the program is running. As both programs are written, if the filename is to change, a programmer must modify the external filename embedded in the call to open() and recompile the program. Both these problems can be avoided by assigning the filename to a string variable. P. 395 Point of Information: Using C-Strings as Filenames If you use a C-string (which is simply a one-dimensional array of characters) to store an external filename, you must specify the C-string's maximum length in brackets immediately after it's declared. For example, examine the following declaration: The number in brackets (21) is one more than the maximum number of characters that can be assigned to the variable filename because the compiler adds an end-of-string character to terminate the string. Therefore, the string value prices.dat, which consists of 10 characters, is actually stored as 11 characters. In this example, the maximum value that can be assigned to the string variable filename is a string value consisting of 20 characters. In declaring and initializing a string variable for use in an open() method, the variable must represent a C-string, a one-dimensional array of characters terminated with a null character. (See the Point of Information Using C-Strings as Filenames for precautions when using a C-string.) A safer alternative, as it doesn't require specifying a character count and one used throughout this book is to use an object created from the string class. To do this, add an #include <string> directive, declare an object to be of this class, and convert the object to a C-string in the open() method call by using the string class method c_str(). After a string variable is declared to store a filename, it can be used in one of two ways. First, as shown in Program 9.3a, it can be used to avoid embedding a filename in the open() method by placing the declaration statement at the top of a program. This method also clearly identifies the file's name up front. Program 9.3a

9 Page 9 of 34 P. 396 In Program 9.3a, the string object is declared and initialized with the name filename. 1 This name is placed at the top of main() for easy file identification and modification. When a string object is used, as opposed to a string literal, the object name isn't enclosed in double quotation marks in the open() method call. However, because open() requires a C-string (the string class doesn't use C-strings), the string object must be converted to a C-string in the open() call, which is done by using the c_str() method in the expression filename.c_str(). Finally, in the fail() method, the file's external name is displayed by inserting the string object's name in the cout output stream. External names of files are identified in this manner in this book. Another useful role string objects play is to permit users to enter the filename as the program is running. For example, the code allows a user to enter a file's external name at runtime. The only restriction in this code is that the user must not enclose the entered string value in double quotation marks, and the entered string value can't contain any blanks. The reason no blanks can be included is that when cin is used, the compiler terminates the string when it encounters a blank. Program 9.3b uses this code in the context of a complete program.

10 Page 10 of 34 P. 397 Program 9.3b The following is a sample output of Program 9.3b: P. 398 Point of Information: A Way to Identify a File's Name and Location During program development, test files are usually placed in the same directory or folder as the program. Therefore, a method call such as infile.open( exper.dat ) causes no problems to the OS. In production systems, however, it's not uncommon for data files to reside in one folder and program files to reside in another. For this reason, including the full pathname of any file that's opened is always a good idea. For example, if the exper.dat file resides in the C:\test\files directory, the open() call should include the full pathname: infile.open ( C:\\test\\files\\exper.dat ). Then, no matter where the program is run from, the OS knows where to locate the file. Note the use of double backslashes, which is required.

11 Page 11 of 34 Another important convention is to list all filenames at the top of a program instead of embedding the names deep in the code. You can do this easily by declaring each filename as a string object (or a one-dimensional array of characters). For example, placing the following statement at the top of a program file clearly lists both the name of the file and its location: If some other file is to be tested, all that's required is a simple change to the string literal in this easy-to-find statement. Remember that using the string class requires adding the #include <string> directive in your program. Closing a File A file is closed by using the close() method. This method breaks the connection between the file's external name and the file stream object, which can be used for another file. Examine the following statement, which closes the infile stream's connection to its current file: As indicated, the close() method takes no argument. Because all computers have a limit on the maximum number of files that can be open at one time, closing files that are no longer needed makes good sense. Any open files existing at the end of normal program execution are closed automatically by the OS. P. 399 Point of Information: Using fstream Objects In using ifstream and ofstream objects, the input or output mode is indicated by the object. Therefore, ifstream objects must be used for input, and ofstream objects must be used for output. Another means of creating file streams is with fstream objects that can be used for input or output, but this method requires an explicit mode designation. An fstream object is declared by using the following syntax: When using the fstream class's open() method, two arguments are required: a file's external name and a mode indicator. Here are the permissible mode indicators; except for the first two, they can also be used when opening ifstream and ofstream objects: As with ofstream objects, an fstream object in output mode creates a new file and makes the file available for writing. If a file exists with the same name as a file opened for output, the old file is erased. For example, the following statement declares file1 as an object of type fstream: The following statement attempts to open the text file prices.dat for output: After this file has been opened, the program accesses the file by using the internal object name file1, and the computer saves the file under the external name prices.dat.

12 Page 12 of 34 An fstream file object opened in append mode means an existing file is available for data to be added to the end of the file. If the file opened for appending doesn't exist, a new file with the designated name is created and made available to receive output from the program. For example, the following statement declares file1 as an fstream object and attempts to open a text file named prices.dat and make it available for data to be added to the end of the file: P. 400 Finally, an fstream object opened in input mode means an existing external file has been connected and its data is available as input. For example, the following statement declares file1 to be of type fstream and attempts to open a text file named prices.dat for input: Mode indicators can be combined by the bitwise OR operator, (see Appendix C, available online). For example, the following statement opens the file1 stream, which can be an fstream or ifstream object, as an input binary stream: If the mode indicator is omitted as the second argument for an ifstream object, the stream is opened as a text input file by default; if the mode indicator is omitted for an ofstream object, the stream is opened as a text output file by default. Exercises (Practice) Write declaration and open statements that link the following external filenames to their corresponding internal filenames. All files are text-based. 2. (Practice) a. Write a set of two statements that declares the following objects as ifstream objects and then opens them as text input files: indata.txt, prices.txt, coupons.dat, and exper.dat. b. Rewrite the two statements for Exercise 2a, using a single statement. 3. (Practice) a. Write a set of two statements declaring the following objects as ofstream objects and then opening them as text output files: outdate.txt, rates.txt, distance.txt, and file2.txt. b. Rewrite the two statements for Exercise 3a, using a single statement. P. 401 Point of Information: Checking for a Successful Connection You should always check that the open() method established a connection between a file stream and an external file successfully because the open() call is a request to the OS that can fail for various reasons. Chief among these reasons is a request to open an existing file for reading that the OS can't locate or a request to open a file for output in a nonexistent folder. If the OS can't satisfy the

13 Page 13 of 34 open request, you need to know about it and terminate your program. Failure to do so can result in abnormal program behavior or a program crash. The most common method for checking that a fail didn't occur when attempting to use a file for input is the one coded in Program 9.1, which uses separate calls to the open() and fail() methods. Similarly, the check made in Program 9.2 is typically included when a file is being opened in output mode. Alternatively, you might encounter programs that use fstream objects in place of ifstream and ofstream objects (see the previous Point of Information box). Except for the open() method (which requires two arguments: a file's external name and a mode indicator), the fail() method is called the same as in Program 9.1 or Program 9.2. In all these cases, you can substitute the expression!infile for the conditional expression infile.fail(). 4. (Practice) Enter and run Program 9.1 on your computer. 5. (Practice) Enter and run Program 9.2 on your computer. 6. (Practice) a. Enter and run Program 9.3a on your computer. b. Add a close() method to Program 9.3a, and then run the program. 7. (Practice) a. Enter and run Program 9.3b on your computer. b. Add a close() method to Program 9.3b, and then run the program. 8. (Practice) Using the reference manuals provided with your computer's OS, determine the following: a. The maximum number of characters the computer can use to name a file for storage b. The maximum number of data files that can be open at the same time 9. (Practice) Is calling a saved C++ program a file appropriate? Why or why not? P (Practice) a. Write declaration and open statements to link the following external filenames to their corresponding internal filenames. Use only ifstream and ofstream objects. b. Redo Exercise 10a, using only fstream objects. c. Write close() statements for each file opened in Exercise 10a. 9.2 Reading and Writing Text Files Reading or writing text files involves almost the identical operations for reading input from the keyboard and writing data to the screen. For writing to a file, the cout object is replaced by the ofstream object name declared in the program. For example, if outfile is declared as an object of type ofstream, the following output statements are valid: The filename in each of these statements, in place of cout, directs the output stream to a specific file instead of to the screen. Program 9.4 shows using the insertion operator, <<, to write a list of descriptions and prices to a file. When Program 9.4 runs, the, prices.dat file is created and saved by the computer as a text file (the default file type) in the same folder where the program is located. It's a sequential file consisting of the following data:

14 Page 14 of 34 The actual storage of characters in the file depends on the character codes the computer uses. Although only 30 characters appear to be stored in the file corresponding to the descriptions, blanks, and prices written to the file the file contains 36 characters. P. 403 Program 9.4 The extra characters consist of the newline escape sequence at the end of each line created by the endl manipulator, which is created as a carriage return character (cr) and linefeed (lf). Assuming characters are stored with the ASCII code, the prices.dat file is physically stored as shown in Figure 9.2. For convenience, the character corresponding to each hexadecimal code is listed below the code. A code of 20 represents the blank character. Additionally, P. 404 Point of Information: Formatting Text File Output Stream Data Output file streams can be formatted in the same manner as the cout standard output stream. For example, if an output stream named fileout has been declared, the following statement formats all data inserted in the fileout stream in the same way these manipulators work for the cout stream:

15 Page 15 of 34 The first manipulator parameter, ios::fixed, causes the stream to output all numbers as though they were floating-point values. The next parameter, ios::showpoint, tells the stream to always provide a decimal point. Therefore, a value such as 1.0 appears as 1.0, not as 1, which doesn't contain a decimal point. Finally, the setprecision() manipulator tells the stream to display two decimal values after the decimal point. Therefore, the number 1.0, for example, appears as Instead of using manipulators, you can use the stream methods setf() and precision(). For example, the previous formatting can be accomplished with the following code: The style you select is a matter of preference. In both cases, the formats need be specified only once and remain in effect for every number subsequently inserted in the file stream. C and C++ append the low-value hexadecimal byte 0x00 as the end-of-file (EOF) sentinel when the file is closed. This EOF sentinel is never counted as part of the file. prices.dat file as stored by the computer Figure 9.2 The P. 405 Point of Information: Writing One Character at a Time with the put() Method All output streams have access to the fstream class's put() method, which permits character-by-character output to a stream. This method works in the same manner as the character insertion operator, <<. The syntax of this method call is the following: The characterexpression can be a character variable or literal value. For example, the following code can be used to output an 'a' to the screen: In a similar manner, if outfile is an ofstream object file that has been opened, the following code outputs the character value in the character variable named keycode to the outfile stream: Reading from a Text File

16 Page 16 of 34 Reading data from a text file is almost identical to reading data from a standard keyboard, except the cin object is replaced by the ifstream object declared in the program. For example, if infile is declared as an object of type ifstream that's opened for input, the following statement reads the next two items in the file and stores them in the variables descrip and price: The file stream name in this statement, in place of cin, directs the input to come from the file stream rather than the keyboard. Table 9.3 lists other methods that can be used for stream input. When called, these methods must be preceded by a stream object name. P. 406 Table 9.3 fstream Methods Method Name Description get() Returns the next character extracted from the input stream as an int. get(charvar) Overloaded version of get() that extracts the next character from the input stream and assigns it to the specified character variable, charvar. getline(strobj, termchar) Extracts characters from the specified input stream, strobj, until the terminating character, termchar, is encountered. Assigns the characters to the specified string class object, strobj. peek() Returns the next character in the input stream without extracting it from the stream. ignore(int n) Skips over the next n characters. If n is omitted, the default is to skip over the next single character. Table 9.3 fstream Methods Program 9.5 shows how the prices.dat file created in Program 9.4 can be read. This program illustrates one way of detecting the EOF marker by using the good() method (see Table 9.2). Because this method returns a Boolean true value before the EOF marker has been read or passed over, it can be used to verify that the data read is valid file data. Only after the EOF marker has been read or passed over does this method return a Boolean false. Therefore, the notation while(infile.good()) used in Program 9.5 ensures that data is from the file before the EOF has been read. P. 407 Program 9.5

17 Page 17 of 34 P. 408 Program 9.5 produces the following display: Examine the expression infile.good() used in the while statement. This expression is true as long as the EOF marker hasn't been read. Therefore, as long as the last character read is good (that is, the EOF marker hasn't been passed), the loop continues to read the file. Inside the loop, the items just read are displayed, and then a new string and a double-precision number are input to the program. When the EOF has been detected, the expression returns a Boolean value of false and the loop terminates. This termination ensures that data is read and displayed up to, but not including, the EOF marker. A replacement for the expression while(infile.good()) is the expression while(!infile.eof()), which is read as while the end of file has not been reached. This replacement works because the eof() method returns a true only after the EOF marker has been read or passed over. In effect, the relational expression checks that the EOF hasn't been read hence, the use of the NOT operator,!. Another means of detecting the EOF is to use the fact that the extraction operator, >>, returns a Boolean value of true if data is extracted from a stream; otherwise, it returns a Boolean false value. Using this return value, the following code can be used in Program 9.5 to read the file: Although this code seems a bit cryptic at first glance, it makes perfect sense when you understand that the expression being tested extracts data from the file and returns a Boolean value to indicate whether the extraction was successful. Finally, in the previous while statement or in Program 9.5, the expression infile >> descrip >> price can be replaced by a getline() method (see Table 9.3). For file input, this method has the following syntax:

18 Page 18 of 34 fileobject is the name of the ifstream file, strobj is a string class object, and terminatingchar is an optional character constant or variable specifying the terminating character. If this optional third argument is omitted, the default terminating character is the newline ('\n') character. Program 9.6 shows using getline() in the context of a complete program. P. 409 Program 9.6 Program 9.6 is a line-by-line text-copying program, which reads a line of text from the file and then displays it on the screen. This program's output is the following: If obtaining the description and price as separate variables is necessary, either Program 9.5 should be used, or the string returned by getline() in Program 9.6 must be processed further to extract the separate data items. (See Section 9.7 for parsing procedures.) P. 410 Point of Information: The get() and putback() Methods All input streams have access to the fstream class's get() method, used for character-by-character input from an input stream. This method works similarly to character extraction, using the >> operator, with two important differences: If a newline character, '\n', or

19 Page 19 of 34 a blank character, ' ', is encountered, these characters are read in the same manner as any other alphanumeric character. The syntax of this method call is the following: For example, the following code can be used to read the next character from the standard input stream and store the character in the variable ch: Similarly, if infile is an ifstream object that has been opened to a file, the following code reads the next character in the stream and assigns it to the character variable keycode: In addition to the get() method, all input streams have a putback() method for putting the last character read from an input stream back on the stream. This method has the following syntax (with characterexpression representing any character variable or character value): The putback() method provides output capability to an input stream. The putback character need not be the last character read; it can be any character. All putback characters, however, have no effect on the data file. They affect only the open input stream. Therefore, the data file characters remain unchanged, although the characters subsequently read from the input stream can change. Standard Device Files The file stream objects you have seen so far have been logical file objects. A logical file object is a stream that connects a file of logically related data, such as a data file, to a program. In addition, C++ supports a physical file object, which is a stream that connects to a hardware device, such as a keyboard, screen, or printer. The actual physical device assigned to your program for data entry is formally called the standard input file. Usually, it's the keyboard. When a cin object method call is encountered in a C++ program, it's a request to the OS to go to this standard input file for the expected input. Similarly, when a cout object method call is encountered, the output is automatically displayed P. 411 or written to a device that has been assigned as the standard output file. For most systems, it's a computer screen, although it can also be a printer. When a program including the iostream header file is executed, the standard input stream cin is connected to the standard input device. Similarly, the standard output stream cout is connected to the standard output device. These two object streams are available for programmer use, as are the standard error stream, cerr, and the standard log stream, clog. Both these streams connect to the screen. Other Devices The keyboard, display, error, and log streams are connected automatically to the stream objects cin, cout, cerr, and clog when the iostream header file is included in a program. Other devices can be used for input or output if the name the system assigns is known. For example, most PCs assign the name prn to the printer connected to the computer. For these computers, a statement such as outfile.open( prn ) connects the printer to the ofstream object named outfile. A subsequent statement, such as outfile << Hello World! ;, would cause the string Hello World! to be output directly to the printer. As the name of an actual file, prn must be enclosed in double quotation marks in the open() method call. Exercises (Practice and Modify) a. Enter and run Program 9.5. b. Modify Program 9.5 to use the expression!infile.eof() in place of the expression infile.good(), and run the program to see whether it operates correctly.

20 Page 20 of (Practice and Modify) a. Enter and run Program 9.6. b. Modify Program 9.6 by replacing cout with cerr, and verify that the output for the standard error file stream is the screen. c. Modify Program 9.6 by replacing cout with clog, and verify that the output for the standard log stream is the screen. 3. (Practice and Modify) a. Write a C++ program that accepts lines of text from the keyboard and writes each line to a file named text.dat until an empty line is entered. An empty line is a line with no text that's created by pressing the Enter (or Return) key. b. Modify Program 9.6 to read and display the data stored in the text.dat file created in Exercise 3a. 4. (Practice) Determine the OS command or procedure your computer provides to display the contents of a saved file. 5. (Program) a. Create a text file named employee.dat containing the following data: Anthony A /18/2010 Burrows W /9/2011 Fain B /18/2011 Janney P /28/2008 Smith G /20/2006 P. 412 b. Write a C++ program to read the employee.dat file created in Exercise 5a and produce a duplicate copy of the file named employee.bak. c. Modify the program written in Exercise 5b to accept the names of the original and duplicate files as user input. d. The program written for Exercise 5c always copies data from an original file to a duplicate file. What's a better method of accepting the original and duplicate filenames, other than prompting the user for them each time the program runs? 6. (Program) a. Write a C++ program that opens a file and displays its contents with line numbers. That is, the program should print the number 1 before displaying the first line, print the number 2 before displaying the second line, and so on for each line in the file. b. Modify the program written in Exercise 6a to list the file's contents on the printer assigned to your computer. 7. (Program) a. Create a text file named info.dat containing the following data (without the headings): Name Social Security Number Hourly Rate Hours Worked B Caldwell D Memcheck R Potter W Rosen b. Write a C++ program that reads the data file created in Exercise 7a and computes and displays a payroll schedule. The output should list the Social Security number, name, and gross pay for each person, calculating gross pay as Hourly Rate Hours Worked. 8. (Program) a. Create a text file named car.dat containing the following data (without the headings): Car Number Miles Driven Gallons of Gas Used

21 Page 21 of 34 b. Write a C++ program that reads the data in the file created in Exercise 8a and displays the car number, miles driven, gallons of gas used, and miles per gallon (mpg) for each car. The output should contain the total miles driven, total gallons of gas used, and average mpg for all cars. These totals should be displayed at the end of the output report. P (Program) a. Create a text file named parts.dat with the following data (without the headings): Part Number Initial Amount Quantity Sold Minimum Amount QA CM MS EN b. Write a C++ program to create an inventory report based on the data in the file created in Exercise 9a. The display should consist of the part number, current balance, and the amount needed to bring the inventory to the minimum level. The current balance is the initial amount minus the quantity sold. 10. (Program) a. Create a text file named pay.dat containing the following data (without the headings): Name Rate Hours Callaway, G Hanson, P Lasard, D Stillman, W b. Write a C++ program that uses the information in the file created in Exercise 10a to produce the following pay report for each employee: Compute regular pay as any hours worked up to and including 40 hours multiplied by the pay rate. Compute overtime pay as any hours worked above 40 hours at a pay rate of 1.5 multiplied by the regular rate. The gross pay is the sum of regular and overtime pay. At the end of the report, the program should display the totals of the regular, overtime, and gross pay columns. 11. (Program) a. Store the following data in a file named numbers.dat: b. Write a C++ program to calculate and display the average of each group of numbers in the file created in Exercise 11a. The data is arranged in the file so that each group of numbers is preceded by the number of data items in the group. Therefore, the first number in the file, 5, indicates that the next five numbers should be grouped together. The number 4 indicates that the following four numbers are a group, and the 6 indicates that the last six numbers are a group. (Hint: Use a nested loop. The outer loop should terminate when the end of file has been encountered.) P (Program) Write a C++ program that allows users to enter the following information from the keyboard for each student in a class (up to 20 students) and stores the data in a text file named grade.dat: For each student, your program should first calculate a final grade, using this formula: Final Grade = 0.20 Exam Exam Homework Final Exam

22 Page 22 of 34 Then assign a letter grade on the basis of = A, = B, = C, = D, and less than 60 = F. All the information, including the final grade and the letter grade, should then be displayed and written to a file. 13. (Program) A bank's customer records are to be stored in a file and read into a set of arrays so that a customer's record can be accessed randomly by account number. Create the file by entering five customer records, with each record consisting of an integer account number (starting with account number 1000), a first name (maximum of 10 characters), a last name (maximum of 15 characters), and a double-precision number for the account balance. After the file is created, write a C++ program that requests a user-input account number and displays the corresponding name and account balance from the file. (Hint: Read the data in the file into an array, and then search the array for the account number.) 14. (Program) Create a text file with the following data or use the shipped.dat file provided on this book's Web site. The headings aren't part of the file; they simply indicate what the data represents. Shipped Date Tracking Number Part Number First Name Last Name Company 04/12/11 D James Lehoff Rotech 04/12/11 D Janet Lezar Rotech 04/12/11 D Bill McHenry Rotech 04/12/11 D Diane Kaiser Rotech 04/12/11 D Helen Richardson NapTime The format of each line in the file is identical, with fixed-length fields defined as follows: Field Position Field Name Starting Col. No. Ending Col. No. Field Length 1 Shipped Date Tracking Number Part Number First Name Last Name Company P. 415 Using this data file, write a C++ program that reads the file and produces a report listing the shipped date, part number, first name, last name, and company name. 9.3 Random File Access The term file access refers to the process of retrieving data from a file. There are two types of file access: sequential access and random access. To understand file access types, first you need to understand how data is organized in a file. The term file organization refers to the way data is stored in a file. The files you have used, and will continue to use, have a sequential organization, meaning characters in the file are stored in a sequential manner. In addition, each open file has been read in a sequential manner, meaning characters are accessed one after another, which is called sequential access. Although characters are stored sequentially, they don't have to be accessed the same way. In fact, you can skip over characters and read a sequentially organized file in a nonsequential manner. In random access, any character in the opened file can be read without having to sequentially read all characters stored ahead of it first. To provide random access to files, each ifstream object creates a file position marker automatically that keeps track of where the next character is to be read from or written to. Table 9.4 lists the methods used to access and change the file position marker. The suffixes g and p in these method names denote get and put; get refers to an input (get from) file, and put refers to an output (put to) file. Table 9.4 File Position Marker Methods Name Description seekg(offset, mode) For input files, move to the offset position indicated by the mode. seekp(offset, mode) For output files, move to the offset position indicated by the mode. tellg(void) For input files, return the current value of the file position marker. tellp(void) For output files, return the current value of the file position marker.

23 Page 23 of 34 Table 9.4 File Position Marker Methods To understand these methods, you must know how data is referenced in the file by using the file position marker and how an offset can be used to alter the file position marker's value. Each character in a data file is located by its position in the file. The first character in the file is located at position 0, the next character at position 1, and so forth. The file position marker contains the positional value, starting from the first character in the file, of where the next character is to be read from or written. Therefore, if the first character is accessed (read from or written to), the file position marker is 0; if the second character is to be accessed, the file position marker is 1, and so on, for each character in the file. By adjusting the file position marker's value, the seek() methods enable the programmer to move to any position in the file. This adjustment is specified by an offset value. P. 416 The seek() methods require two arguments: an offset value, as a long integer, and what position in the file the offset is to be applied to, determined by the mode. The three available modes are ios::beg, ios::cur, and ios::end, which denote the beginning of the file, current position, and end of the file. Therefore, the mode ios::beg means the offset is relative to the position of the first character in the file. The mode ios::cur means the offset is relative to the current position in the file, and the mode ios::end means the offset is relative to the last character in the file. From a practical standpoint, a positive offset means move forward in the file from the designated starting position, and a negative offset means move backward from this position. Examples of seek() method calls are shown in the following code. In these examples, infile has been opened as an input file and outfile as an output file. The offset passed to seekg() and seekp() must be a long integer, hence the uppercase L appended to each number in the method calls. As opposed to seek() methods that move the file position marker, the tell() methods return the file position marker's offset value. For example, if 10 characters have been read from an input file named infile, the method call returns the long integer 10: This method call means the next character to be read is offset 10 byte positions from the start of the file and is the 11th character in the file. Program 9.7 shows using seekg() and tellg() to read a file in reverse order, from the last character to the first. As each character is read, it's also displayed.

24 Page 24 of 34 P. 417 Program 9.7

25 Page 25 of 34 Assume the test.dat file contains the following characters: P. 418 The output of Program 9.7 is the following:

26 Page 26 of 34 Program 9.7 initially goes to the last character in the file. The offset of this character, the EOF character, is saved in the variable last. Because tellg() returns a long integer, last has been declared as a long integer. Starting from the end of the file, seekg() is used to position the next character to be read, referenced from the end of the file. As each character is read, it's displayed, and the offset is adjusted to access the next character. The first offset used is -1, which represents the character immediately preceding the EOF marker. Exercises (Practice) a. Create a file named test.dat containing the data in the test.dat file used in Program 9.7. (You can use a text editor or copy the test.dat file from this book's Web site.) b. Enter and run Program 9.7 on your computer. 2. (Modify) Rewrite Program 9.7 so that the origin for the seekg() method used in the for loop is the start of the file rather than the end. 3. (Modify) Modify Program 9.7 to display an error message if seekg() attempts to reference a position beyond the end of file. 4. (Practice) Write a program that reads and displays every second character in a file named test.dat. 5. (Practice) Using the seek() and tell() methods, write a function named filechars() that returns the total number of characters in a file. 6. (Practice) a. Write a function named readbytes() that reads and displays n characters starting from any position in a file. The function should accept three arguments: a file object name, the offset of the first character to be read, and the number of characters to be read. (Note: The prototype for readbytes() should be void readbytes(fstream&, long, int).) b. Modify the readbytes() function written in Exercise 6a to store the characters read into a string or an array. The function should accept the storage address as a fourth argument. 9.4 File Streams as Function Arguments A file stream object can be used as a function argument. The only requirement is that the function's formal parameter be a reference (see Section 6.3) to the correct stream: ifstream& or ofstream&. For example, in Program 9.8, an ofstream object named outfile is opened in main(), and this stream object is passed to the inout() function. The function prototype and header for inout() declare the formal parameter as a reference to an ostream object type. The inout() function is then used to write five lines of user-entered text to the file. P. 419 Program 9.8

27 Page 27 of 34 P. 420 In main(), the file is an ostream object named outfile. This object is passed to the inout() function and accepted as the formal parameter fileout, which is declared as a reference to an ostream object type. The inout() function then uses its reference

28 Page 28 of 34 parameter outfile as an output file stream name in the same manner that main() would use the fileout stream object. Program 9.8 uses the getline() method introduced in Section 9.2 (see Table 9.3). Program 9.9 expands on Program 9.8 by adding a getopen() function to perform the open. Like inout(), getopen() accepts a reference argument to an ofstream object. After getopen() finishes executing, this reference is passed to inout(), as in Program 9.8. Although you might be tempted to write getopen() to return a reference to an ofstream, it won't work because it results in an attempt to assign a returned reference to an existing one. Program 9.9 P. 421

29 Page 29 of 34 Program 9.9 allows the user to enter a filename from the standard input device and then opens the ofstream connection to the external file. If an existing data file's name is entered, the file is destroyed when it's opened for output. A useful trick for preventing this mishap is shown in the shaded code in Program 9.2. Exercises (Practice) A function named pfile() is to receive a filename as a reference to an ifstream object. What declarations are required to pass a filename to pfile()? 2. (Practice) Write a function named fcheck() that checks whether a file exists. The function should accept an ifstream object as a formal reference parameter. If the file exists, the function should return a value of 1; otherwise, the function should return a value of (Practice) A data file consisting of a group of lines has been created. Write a function named printline() that reads and displays any line of the file. For example, the function called printline(fstream& fname,5); should display the fifth line of the passed object stream. P (Modify) Rewrite the getopen() function used in Program 9.9 to incorporate the file-checking procedures described in this section. Specifically, if the entered filename exists, an appropriate message should be displayed. The user should be given the option of entering a new filename or allowing the program to overwrite the existing file. Use the function written for Exercise 2 in your program. 9.5 Common Programming Errors The common programming errors with files are as follows: 1. Forgetting to open a file before attempting to read from it or write to it. 2. Using a file's external name in place of the internal file stream object name when accessing the file. The only stream method that uses the data file's external name is the open() method. As always, all stream methods discussed in this chapter must be preceded by a stream object name followed by a period (the dot operator).

30 Page 30 of Opening a file for output without first checking that a file with the same name already exists. If it does and you didn't check for a preexisting filename, the file is overwritten. 4. Not understanding that the end of a file is detected only after the EOF marker has been read or passed over. 5. Attempting to detect the end of a file by using character variables for the EOF marker. Any variable used to accept the EOF must be declared as an integer variable. For example, if ch is declared as a character variable, the following expression produces an infinite loop: 2 This problem occurs because a character variable can never take on an EOF code. EOF is an integer value (usually -1) with no character representation, which ensures that the EOF code can't be confused with a legitimate character encountered as normal data in the file. To terminate the loop created by the preceding expression, the variable ch must be declared as an integer variable. 6. Using an integer argument with the seekg() and seekp() functions. This offset must be a long integer constant or variable. Any other value passed to these functions can have unpredictable results. I/O Streams and Data Files: 9.6 Chapter Summary 1. A data file is any collection of data stored together in an external storage medium under a common name. 2. A data file is connected to a file stream by using a file stream object. P File stream objects are created from the ifstream, ofstream, or fstream classes. File stream objects declared as ifstream objects are created as input streams, and file streams declared as ofstream objects are created as output streams. File stream objects declared as fstream objects must indicate the type of stream explicitly. To do this, use declaration statements similar to the following (infile and outfile are user-selected object names): 4. After a file stream object is created, it's connected to a file by using an open() method. This method connects a file's external name with an internal stream object name. After the file is opened, all subsequent accesses to it require the internal stream object name. 5. An opened output file stream creates a new data file or erases the data in an existing opened file. An opened input file stream makes an existing file's data available for input. An error condition results if the file doesn't exist and can be detected by using the fail() method. 6. In addition to any files opened in a function, the standard stream objects cin, cout, and cerr are declared and opened automatically when a program runs. cin is an input file stream object used for data entry (usually from the keyboard), cout is an output file stream object used for data display (usually onscreen), and cerr is an output file stream object used for displaying system error messages (usually onscreen). 7. Data files can be accessed randomly by using the seekg(), seekp(), tellg(), and tellp() methods. The g versions of these methods are used to alter and query the file position marker for input file streams, and the p versions do the same for output file streams. 8. Table 9.5 lists class-supplied methods for file manipulation. The getline() method is defined in the string class, and all other methods are defined in the fstream class. These methods can be used by all ifstream and ofstream files. Table 9.5 File Manipulation Methods Method Name Description get() Extract the next character from the input stream and return it as an int. get(chrvar) Extract the next character from the input stream and assign it to chrvar. getline(fileobj, string, termchar) Extract the next string of characters from the input file stream object and assign them to string until the specified terminating character is detected.if omitted, the default terminating character is a newline. Table 9.5 File Manipulation Methods P. 424 Table 9.5 File Manipulation Methods (continued) Method Name Description Extract and return characters from the input stream until n-1 characters are read or a newline is encountered (terminates the input with a '\0').

31 Page 31 of 34 Table 9.5 File Manipulation Methods (continued) Method Name Description getline (C-stringVar,int n,'\n') peek() Return the next character in the input stream without extracting it from the stream. put(chrexp) Put the character specified by chrexp on the output stream. putback(chrexp) Push the character specified by chrexp back onto the input stream. Does not alter the data in the file. ignore(int n) Skip over the next n characters; if n is omitted, the default is to skip over the next single character. eof() Returns a Boolean true if a read has been attempted past the end of file; otherwise, it returns a Boolean false. The value becomes true only when the first character after the last valid file character is read. good() Returns a Boolean true while the file is available for program use. Returns a Boolean false if a read has been attempted past the end of file. The value becomes false only when the first character after the last valid file character is read. bad() Returns a Boolean true if a read has been attempted past the end of file; otherwise, it returns a false. The value becomes true only when the first character after the last valid file character is read. fail() Returns a Boolean true if the file hasn't been opened successfully; otherwise, it returns a Boolean false. Table 9.5 File Manipulation Methods (continued) P. 425 I/O Streams and Data Files: 9.7 Chapter Supplement: The iostream Class Library As you have seen, the classes in the iostream class library access files by using entities called streams. For most systems, the data bytes transferred on a stream represent ASCII characters or binary numbers. The mechanism for reading a byte stream from a file or writing a byte stream to a file is hidden when using a high-level language, such as C++. Nevertheless, understanding this mechanism is useful so that you can place the services provided by the iostream class library in context. File Stream Transfer Mechanism Figure 9.3 illustrates the mechanism for transferring data between a program and a file. As shown, this transfer involves an intermediate file buffer contained in the computer's memory. Each opened file is assigned its own file buffer, which is a storage area used by the data transferred between the program and the file. 9.3 The data transfer mechanism Figure The program either writes a set of data bytes to the file buffer or reads a set of data bytes from the file buffer by using a stream object. The data transfer between the device storing the data file (usually a disk or CD/DVD) and the file buffer is handled by special OS programs. These programs, called device drivers, aren't stand-alone programs; they're an integral part of the OS. A device driver is a section of OS code that accesses a hardware device, such as a disk, and handles the data transfer between the device and the computer's memory. Because the computer's internal data transfer rate is generally much faster than any device connected to it, the device driver must correctly synchronize the data transfer speed between the computer and the device sending or receiving data. Typically, a disk device driver transfers data between the disk and file buffer only in fixed sizes, such as 1024 bytes at a time. Therefore, the file buffer is a convenient means of permitting a device driver to transfer data in blocks of one size, and the program can access them by using a different size (typically, as separate characters or as a fixed number of characters per line).

32 Page 32 of 34 Components of the iostream Class Library The iostream class library consists of two primary base classes: streambuf and ios. The streambuf class provides the file buffer, shown in Figure 9.3, and general routines for transferring binary data. The ios class contains a pointer to the file buffers provided by the P. 426 streambuf class and general routines for transferring text data. From these two base classes, several other classes are derived and included in the iostream class library. Figure 9.4 is an inheritance diagram for the ios family of classes as it relates to the ifstream, ofstream, and fstream classes. Figure 9.5 is an inheritance diagram for the streambuf family of classes. In these diagrams, the arrows point from a derived class to a base class, so they're actually easier to read from top to bottom. For example, Figure 9.4 indicates that all the stream objects shown are derived from the ios class, and the ifstream class is derived from both the fstream and istream classes. In all cases, a derived class has full access to all methods of its base class. its derived classes Figure 9.4 The base class ios and derived classes Figure 9.5 The base class streambuf and its Table 9.6 lists the correspondence between the classes shown in Figures 9.4 and 9.5, including the header files defining these classes. P. 427

33 Page 33 of 34 Table 9.6 Correspondence Between Classes in Figures 9.4 and 9.5 Therefore, the ifstream, ofstream, and fstream classes you have used for file access use a buffer provided by the filebuf class and defined in the fstream header file. Similarly, the cin, cout, cerr, and clog iostream objects use a buffer provided by the streambuf class and defined in the iostream header file. In-Memory Formatting In addition to the classes shown in Figure 9.5, a class named strstream is derived from the ios class. This class uses the strstreambuf class shown in Figure 9.5, requires the strstream header file, and provides capabilities for writing and reading strings to and from in-memory defined streams. When created as an output stream, in-memory streams are typically used to assemble a string from smaller pieces until a complete line of characters is ready to be written to cout or to a file. Attaching a strstream object to a buffer for this purpose is similar to attaching an fstream object to an output file. For example, the statement creates a strstream object named buf to have a capacity of 72 bytes in output mode. Program 9.10 shows how this statement is used in the context of a complete program. Program 9.10 produces the following output: This output illustrates that the character buffer has been filled in correctly by insertions to the inmem stream. (Note that the end-ofstring NULL, '\0', which is the last insertion to the stream, is required to close off the C-string correctly.) After the character array has been filled, it's written to a file as a single string. P. 428 Program 9.10

Chapter 7 : Arrays (pp )

Chapter 7 : Arrays (pp ) Page 1 of 45 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York

CSc Introduc/on to Compu/ng. Lecture 19 Edgardo Molina Fall 2011 City College of New York CSc 10200 Introduc/on to Compu/ng Lecture 19 Edgardo Molina Fall 2011 City College of New York 18 Standard Device Files Logical file object: Stream that connects a file of logically related data to a program

More information

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() {

Text File I/O. #include <iostream> #include <fstream> using namespace std; int main() { Text File I/O We can use essentially the same techniques we ve been using to input from the keyboard and output to the screen and just apply them to files instead. If you want to prepare input data ahead,

More information

C++ Programming Lecture 10 File Processing

C++ Programming Lecture 10 File Processing C++ Programming Lecture 10 File Processing By Ghada Al-Mashaqbeh The Hashemite University Computer Engineering Department Outline Introduction. The Data Hierarchy. Files and Streams. Creating a Sequential

More information

C++ does not, as a part of the language, define how data are sent out and read into the program

C++ does not, as a part of the language, define how data are sent out and read into the program Input and Output C++ does not, as a part of the language, define how data are sent out and read into the program I/O implementation is hardware dependent The input and output (I/O) are handled by the standard

More information

Chapter 3 - Notes Input/Output

Chapter 3 - Notes Input/Output Chapter 3 - Notes Input/Output I. I/O Streams and Standard I/O Devices A. I/O Background 1. Stream of Bytes: A sequence of bytes from the source to the destination. 2. 2 Types of Streams: i. Input Stream:

More information

Chapter-12 DATA FILE HANDLING

Chapter-12 DATA FILE HANDLING Chapter-12 DATA FILE HANDLING Introduction: A file is a collection of related data stored in a particular area on the disk. Programs can be designed to perform the read and write operations on these files.

More information

CPE Summer 2015 Exam I (150 pts) June 18, 2015

CPE Summer 2015 Exam I (150 pts) June 18, 2015 Name Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. You can assume that there is one

More information

Chapter 14 Sequential Access Files

Chapter 14 Sequential Access Files Chapter 14 Sequential Access Files Objectives Create file objects Open a sequential access file Determine whether a sequential access file was opened successfully Write data to a sequential access file

More information

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1]

CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] CSC 138 Structured Programming CHAPTER 4: TEXT FILE [PART 1] LEARNING OBJECTIVES Upon completion, you should be able to: o define C++ text files o explain the benefits of using I/O file processing o explain

More information

Chapter 6 : Modularity Using Functions (pp )

Chapter 6 : Modularity Using Functions (pp ) Page 1 of 56 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

Fall 2017 CISC/CMPE320 9/27/2017

Fall 2017 CISC/CMPE320 9/27/2017 Notices: CISC/CMPE320 Today File I/O Text, Random and Binary. Assignment 1 due next Friday at 7pm. The rest of the assignments will also be moved ahead a week. Teamwork: Let me know who the team leader

More information

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points)

CPE 112 Spring 2015 Exam II (100 pts) March 4, Definition Matching (8 Points) Name Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Relational Expression Iteration Counter Count-controlled loop Loop Flow

More information

IS 0020 Program Design and Software Tools

IS 0020 Program Design and Software Tools 1 IS 0020 Program Design and Software Tools Stack/Queue - File Processing Lecture 10 March 29, 2005 Introduction 2 Storage of data Arrays, variables are temporary Files are permanent Magnetic disk, optical

More information

Streams - Object input and output in C++

Streams - Object input and output in C++ Streams - Object input and output in C++ Dr. Donald Davendra Ph.D. Department of Computing Science, FEI VSB-TU Ostrava Dr. Donald Davendra Ph.D. (Department of Computing Streams - Object Science, input

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents

File I/O. File Names and Types. I/O Streams. Stream Extraction and Insertion. A file name should reflect its contents File I/O 1 File Names and Types A file name should reflect its contents Payroll.dat Students.txt Grades.txt A file s extension indicates the kind of data the file holds.dat,.txt general program input or

More information

Software Design & Programming I

Software Design & Programming I Software Design & Programming I Starting Out with C++ (From Control Structures through Objects) 7th Edition Written by: Tony Gaddis Pearson - Addison Wesley ISBN: 13-978-0-132-57625-3 Chapter 3 Introduction

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley

Chapter 6. I/O Streams as an Introduction to Objects and Classes. Copyright 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Slide 6-3 6.1 Streams and Basic File I/O I/O Streams I/O

More information

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1

Today in CS162. External Files. What is an external file? How do we save data in a file? CS162 External Data Files 1 Today in CS162 External Files What is an external file? How do we save data in a file? CS162 External Data Files 1 External Files So far, all of our programs have used main memory to temporarily store

More information

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects

Chapter Overview. I/O Streams as an Introduction to Objects and Classes. I/O Streams. Streams and Basic File I/O. Objects Chapter 6 I/O Streams as an Introduction to Objects and Classes Overview 6.1 Streams and Basic File I/O 6.2 Tools for Stream I/O 6.3 Character I/O Copyright 2008 Pearson Addison-Wesley. All rights reserved.

More information

C++ Input/Output Chapter 4 Topics

C++ Input/Output Chapter 4 Topics Chapter 4 Topics Chapter 4 Program Input and the Software Design Process Input Statements to Read Values into a Program using >>, and functions get, ignore, getline Prompting for Interactive Input/Output

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 The C++ standard libraries provide an extensive set of input/output capabilities. C++ uses type-safe I/O. Each I/O operation is executed in a manner sensitive to the data type. If an I/O member function

More information

File Operations. Lecture 16 COP 3014 Spring April 18, 2018

File Operations. Lecture 16 COP 3014 Spring April 18, 2018 File Operations Lecture 16 COP 3014 Spring 2018 April 18, 2018 Input/Ouput to and from files File input and file output is an essential in programming. Most software involves more than keyboard input and

More information

Random File Access. 1. Random File Access

Random File Access. 1. Random File Access Random File Access 1. Random File Access In sequential file access, the file is read or written sequentially from the beginning. In random file access, you can skip around to various points in the file

More information

What we will learn about this week:

What we will learn about this week: What we will learn about this week: Streams Basic file I/O Tools for Stream I/O Manipulators Character I/O Get and Put EOF function Pre-defined character functions Objects 1 I/O Streams as an Introduction

More information

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class

Piyush Kumar. input data. both cout and cin are data objects and are defined as classes ( type istream ) class C++ IO C++ IO All I/O is in essence, done one character at a time For : COP 3330. Object oriented Programming (Using C++) http://www.compgeom.com/~piyush/teach/3330 Concept: I/O operations act on streams

More information

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes:

C++ Binary File I/O. C++ file input and output are typically achieved by using an object of one of the following classes: C++ Binary File I/O C++ file input and output are typically achieved by using an object of one of the following classes: ifstream for reading input only. ofstream for writing output only. fstream for reading

More information

Chapter 5: Loops and Files

Chapter 5: Loops and Files Chapter 5: Loops and Files 5.1 The Increment and Decrement Operators The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1;

More information

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1

Chapter 5: Prefix vs. Postfix 8/19/2018. The Increment and Decrement Operators. Increment and Decrement Operators in Program 5-1 Chapter 5: Loops and Files The Increment and Decrement Operators ++ is the increment operator. It adds one to a variable. val++; is the same as val = val + 1; ++ can be used before (prefix) or after (postfix)

More information

Full file at

Full file at Java Programming: From Problem Analysis to Program Design, 3 rd Edition 2-1 Chapter 2 Basic Elements of Java At a Glance Instructor s Manual Table of Contents Overview Objectives s Quick Quizzes Class

More information

C++ Input/Output: Streams

C++ Input/Output: Streams C++ Input/Output: Streams Basic I/O 1 The basic data type for I/O in C++ is the stream. C++ incorporates a complex hierarchy of stream types. The most basic stream types are the standard input/output streams:

More information

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York

CSc 10200! Introduction to Computing. Lecture 2-3 Edgardo Molina Fall 2013 City College of New York CSc 10200! Introduction to Computing Lecture 2-3 Edgardo Molina Fall 2013 City College of New York 1 C++ for Engineers and Scientists Third Edition Chapter 2 Problem Solving Using C++ 2 Objectives In this

More information

Streams in C++ Stream concept. Reference information. Stream type declarations

Streams in C++ Stream concept. Reference information. Stream type declarations Stream concept A stream represent a sequence of bytes arriving, being retrieved, being stored, or being sent, in order. A stream is continuos and offer sequential access to the data. Each byte can be read

More information

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 14) 28 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords.

c++ keywords: ( all lowercase ) Note: cin and cout are NOT keywords. Chapter 1 File Extensions: Source code (cpp), Object code (obj), and Executable code (exe). Preprocessor processes directives and produces modified source Compiler takes modified source and produces object

More information

I/O Streams and Standard I/O Devices (cont d.)

I/O Streams and Standard I/O Devices (cont d.) Chapter 3: Input/Output Objectives In this chapter, you will: Learn what a stream is and examine input and output streams Explore how to read data from the standard input device Learn how to use predefined

More information

Expressions, Input, Output and Data Type Conversions

Expressions, Input, Output and Data Type Conversions L E S S O N S E T 3 Expressions, Input, Output and Data Type Conversions PURPOSE 1. To learn input and formatted output statements 2. To learn data type conversions (coercion and casting) 3. To work with

More information

Week 5: Files and Streams

Week 5: Files and Streams CS319: Scientific Computing (with C++) Week 5: and Streams 9am, Tuesday, 12 February 2019 1 Labs and stuff 2 ifstream and ofstream close a file open a file Reading from the file 3 Portable Bitmap Format

More information

Lecture 3 The character, string data Types Files

Lecture 3 The character, string data Types Files Lecture 3 The character, string data Types Files The smallest integral data type Used for single characters: letters, digits, and special symbols Each character is enclosed in single quotes 'A', 'a', '0',

More information

Object Oriented Programming Using C++ UNIT-3 I/O Streams

Object Oriented Programming Using C++ UNIT-3 I/O Streams File - The information / data stored under a specific name on a storage device, is called a file. Stream - It refers to a sequence of bytes. Text file - It is a file that stores information in ASCII characters.

More information

CS2141 Software Development using C/C++ Stream I/O

CS2141 Software Development using C/C++ Stream I/O CS2141 Software Development using C/C++ Stream I/O iostream Two libraries can be used for input and output: stdio and iostream The iostream library is newer and better: It is object oriented It can make

More information

Stream States. Formatted I/O

Stream States. Formatted I/O C++ Input and Output * the standard C++ library has a collection of classes that can be used for input and output * most of these classes are based on a stream abstraction, the input or output device is

More information

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing

Streams. Parsing Input Data. Associating a File Stream with a File. Conceptual Model of a Stream. Parsing. Parsing Input Data 1 Streams 2 Streams Conceptual Model of a Stream Associating a File Stream with a File Basic Stream Input Basic Stream Output Reading Single Characters: get() Skipping and Discarding Characters:

More information

13 File Structures. Source: Foundations of Computer Science Cengage Learning. Objectives After studying this chapter, the student should be able to:

13 File Structures. Source: Foundations of Computer Science Cengage Learning. Objectives After studying this chapter, the student should be able to: 13 File Structures 13.1 Source: Foundations of Computer Science Cengage Learning Objectives After studying this chapter, the student should be able to: Define two categories of access methods: sequential

More information

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved.

C How to Program, 6/e by Pearson Education, Inc. All Rights Reserved. C How to Program, 6/e 1992-2010 by Pearson Education, Inc. An important part of the solution to any problem is the presentation of the results. In this chapter, we discuss in depth the formatting features

More information

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma.

CS 151 Review #3. // More than one variable can be defined // in a statement. Multiple variables are // separated by a comma. REVIEW cout Statement The cout statement invokes an output stream, which is a sequence of characters to be displayed to the screen. cout

More information

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key

Starting Out with C++: Early Objects, 9 th ed. (Gaddis, Walters & Muganda) Chapter 2 Introduction to C++ Chapter 2 Test 1 Key Starting Out with C++ Early Objects 9th Edition Gaddis TEST BANK Full clear download (no formatting errors) at: https://testbankreal.com/download/starting-c-early-objects-9thedition-gaddis-test-bank/ Starting

More information

Convenient way to deal large quantities of data. Store data permanently (until file is deleted).

Convenient way to deal large quantities of data. Store data permanently (until file is deleted). FILE HANDLING Why to use Files: Convenient way to deal large quantities of data. Store data permanently (until file is deleted). Avoid typing data into program multiple times. Share data between programs.

More information

Definition Matching (10 Points)

Definition Matching (10 Points) Name SOLUTION Closed notes and book. If you have any questions ask them. Write clearly and make sure the case of a letter is clear (where applicable) since C++ is case sensitive. There are no syntax errors

More information

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure

Review for COSC 120 8/31/2017. Review for COSC 120 Computer Systems. Review for COSC 120 Computer Structure Computer Systems Computer System Computer Structure C++ Environment Imperative vs. object-oriented programming in C++ Input / Output Primitive data types Software Banking System Compiler Music Player Text

More information

Simple File I/O.

Simple File I/O. Simple File I/O from Chapter 6 http://www.cplusplus.com/reference/fstream/ifstream/ l / /f /if / http://www.cplusplus.com/reference/fstream/ofstream/ I/O Streams I/O refers to a program s input and output

More information

CS242 COMPUTER PROGRAMMING

CS242 COMPUTER PROGRAMMING CS242 COMPUTER PROGRAMMING I.Safa a Alawneh Variables Outline 2 Data Type C++ Built-in Data Types o o o o bool Data Type char Data Type int Data Type Floating-Point Data Types Variable Declaration Initializing

More information

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++

Chapter 5. Repetition. Contents. Introduction. Three Types of Program Control. Two Types of Repetition. Three Syntax Structures for Looping in C++ Repetition Contents 1 Repetition 1.1 Introduction 1.2 Three Types of Program Control Chapter 5 Introduction 1.3 Two Types of Repetition 1.4 Three Structures for Looping in C++ 1.5 The while Control Structure

More information

Chapter 5 : Repetition (pp )

Chapter 5 : Repetition (pp ) Page 1 of 41 Printer Friendly Version User Name: Stephen Castleberry email Id: scastleberry@rivercityscience.org Book: A First Book of C++ 2007 Cengage Learning Inc. All rights reserved. No part of this

More information

by Pearson Education, Inc. All Rights Reserved. 2

by Pearson Education, Inc. All Rights Reserved. 2 Data that is formatted and written to a sequential file as shown in Section 17.4 cannot be modified without the risk of destroying other data in the file. For example, if the name White needs to be changed

More information

Lecture 9. Introduction

Lecture 9. Introduction Lecture 9 File Processing Streams Stream I/O template hierarchy Create, update, process files Sequential and random access Formatted and raw processing Namespaces Lec 9 Programming in C++ 1 Storage of

More information

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018

C++ Basics. Lecture 2 COP 3014 Spring January 8, 2018 C++ Basics Lecture 2 COP 3014 Spring 2018 January 8, 2018 Structure of a C++ Program Sequence of statements, typically grouped into functions. function: a subprogram. a section of a program performing

More information

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space.

3. Except for strings, double quotes, identifiers, and keywords, C++ ignores all white space. Chapter 2: Problem Solving Using C++ TRUE/FALSE 1. Modular programs are easier to develop, correct, and modify than programs constructed in some other manner. ANS: T PTS: 1 REF: 45 2. One important requirement

More information

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files.

This chapter introduces the notion of namespace. We also describe how to manage input and output with C++ commands via the terminal or files. C++ PROGRAMMING LANGUAGE: NAMESPACE AND MANGEMENT OF INPUT/OUTPUT WITH C++. CAAM 519, CHAPTER 15 This chapter introduces the notion of namespace. We also describe how to manage input and output with C++

More information

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input

Formatting outputs String data type Interactive inputs File manipulators. Access to a library that defines 3. instead, a library provides input Input and Output Outline Formatting outputs String data type Interactive inputs File manipulators CS 1410 Comp Sci with C++ Input and Output 1 CS 1410 Comp Sci with C++ Input and Output 2 No I/O is built

More information

Name Section: M/W T/TH Number Definition Matching (8 Points)

Name Section: M/W T/TH Number Definition Matching (8 Points) Name Section: M/W T/TH Number Definition Matching (8 Points) 1. (8 pts) Match the words with their definitions. Choose the best definition for each word. Iteration Counter Event Counter Loop Abstract Step

More information

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file

After going through this lesson, you would be able to: store data in a file. access data record by record from the file. move pointer within the file 16 Files 16.1 Introduction At times it is required to store data on hard disk or floppy disk in some application program. The data is stored in these devices using the concept of file. 16.2 Objectives

More information

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition)

C++ Programming: From Problem Analysis to Program Design, Fourth Edition. Chapter 5: Control Structures II (Repetition) C++ Programming: From Problem Analysis to Program Design, Fourth Edition Chapter 5: Control Structures II (Repetition) Objectives In this chapter, you will: Learn about repetition (looping) control structures

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics 1 Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-3 2.1 Variables and Assignments 2

More information

Fundamentals of Programming Session 27

Fundamentals of Programming Session 27 Fundamentals of Programming Session 27 Instructor: Reza Entezari-Maleki Email: entezari@ce.sharif.edu 1 Fall 2013 These slides have been created using Deitel s slides Sharif University of Technology Outlines

More information

The C++ Language. Arizona State University 1

The C++ Language. Arizona State University 1 The C++ Language CSE100 Principles of Programming with C++ (based off Chapter 2 slides by Pearson) Ryan Dougherty Arizona State University http://www.public.asu.edu/~redoughe/ Arizona State University

More information

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams

Physics 6720 I/O Methods October 30, C++ and Unix I/O Streams Physics 6720 I/O Methods October 30, 2002 We have been using cin and cout to handle input from the keyboard and output to the screen. In these notes we discuss further useful capabilities of these standard

More information

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved.

Chapter 12. Streams and File I/O. Copyright 2016 Pearson, Inc. All rights reserved. Chapter 12 Streams and File I/O Copyright 2016 Pearson, Inc. All rights reserved. Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output, flag

More information

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved

Chapter 12. Streams and File I/O. Copyright 2010 Pearson Addison-Wesley. All rights reserved Chapter 12 Streams and File I/O Copyright 2010 Pearson Addison-Wesley. All rights reserved Learning Objectives I/O Streams File I/O Character I/O Tools for Stream I/O File names as input Formatting output,

More information

Week 3: File I/O and Formatting 3.7 Formatting Output

Week 3: File I/O and Formatting 3.7 Formatting Output Week 3: File I/O and Formatting 3.7 Formatting Output Formatting: the way a value is printed: Gaddis: 3.7, 3.8, 5.11 CS 1428 Fall 2014 Jill Seaman spacing decimal points, fractional values, number of digits

More information

Name Section: M/W T/TH Number Definition Matching (6 Points)

Name Section: M/W T/TH Number Definition Matching (6 Points) Name Section: M/W T/TH Number Definition Matching (6 Points) 1. (6 pts) Match the words with their definitions. Choose the best definition for each word. Event Counter Iteration Counter Loop Flow of Control

More information

بسم اهلل الرمحن الرحيم

بسم اهلل الرمحن الرحيم بسم اهلل الرمحن الرحيم Fundamentals of Programming C Session # 10 By: Saeed Haratian Fall 2015 Outlines Examples Using the for Statement switch Multiple-Selection Statement do while Repetition Statement

More information

Advanced I/O Concepts

Advanced I/O Concepts Advanced Object Oriented Programming Advanced I/O Concepts Seokhee Jeon Department of Computer Engineering Kyung Hee University jeon@khu.ac.kr 1 1 Streams Diversity of input sources or output destinations

More information

C++ Programming: From Problem Analysis to Program Design, Third Edition

C++ Programming: From Problem Analysis to Program Design, Third Edition C++ Programming: From Problem Analysis to Program Design, Third Edition Chapter 2: Basic Elements of C++ Objectives (continued) Become familiar with the use of increment and decrement operators Examine

More information

Chapter 12: Advanced File Operations

Chapter 12: Advanced File Operations Chapter 12: Advanced File Operations 12.1 File Operations File Operations File: a set of data stored on a computer, often on a disk drive Programs can read from, write to files Used in many applications:

More information

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program

2.1. Chapter 2: Parts of a C++ Program. Parts of a C++ Program. Introduction to C++ Parts of a C++ Program Chapter 2: Introduction to C++ 2.1 Parts of a C++ Program Copyright 2009 Pearson Education, Inc. Publishing as Pearson Addison-Wesley 2-1 Parts of a C++ Program Parts of a C++ Program // sample C++ program

More information

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types.

The C++ Language. Output. Input and Output. Another type supplied by C++ Very complex, made up of several simple types. The C++ Language Input and Output Output! Output is information generated by a program.! Frequently sent the screen or a file.! An output stream is used to send information. Another type supplied by C++

More information

CS201 Latest Solved MCQs

CS201 Latest Solved MCQs Quiz Start Time: 09:34 PM Time Left 82 sec(s) Question # 1 of 10 ( Start time: 09:34:54 PM ) Total Marks: 1 While developing a program; should we think about the user interface? //handouts main reusability

More information

Full file at

Full file at Java Programming, Fifth Edition 2-1 Chapter 2 Using Data within a Program At a Glance Instructor s Manual Table of Contents Overview Objectives Teaching Tips Quick Quizzes Class Discussion Topics Additional

More information

Chapter 3: Input/Output

Chapter 3: Input/Output Chapter 3: Input/Output I/O: sequence of bytes (stream of bytes) from source to destination Bytes are usually characters, unless program requires other types of information Stream: sequence of characters

More information

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible)

Multiple Choice (Questions 1 13) 26 Points Select all correct answers (multiple correct answers are possible) Name Closed notes, book and neighbor. If you have any questions ask them. Notes: Segment of code necessary C++ statements to perform the action described not a complete program Program a complete C++ program

More information

Chapte t r r 9

Chapte t r r 9 Chapter 9 Session Objectives Stream Class Stream Class Hierarchy String I/O Character I/O Object I/O File Pointers and their manipulations Error handling in Files Command Line arguments OOPS WITH C++ Sahaj

More information

Lecture 5 Files and Streams

Lecture 5 Files and Streams Lecture 5 Files and Streams Introduction C programs can store results & information permanently on disk using file handling functions These functions let you write either text or binary data to a file,

More information

Object Oriented Programming In C++

Object Oriented Programming In C++ C++ Question Bank Page 1 Object Oriented Programming In C++ 1741059 to 1741065 Group F Date: 31 August, 2018 CIA 3 1. Briefly describe the various forms of get() function supported by the input stream.

More information

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments

Chapter Overview. C++ Basics. Variables and Assignments. Variables and Assignments. Keywords. Identifiers. 2.1 Variables and Assignments Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Copyright 2011 Pearson Addison-Wesley. All rights

More information

Objectives. In this chapter, you will:

Objectives. In this chapter, you will: Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates arithmetic expressions Learn about

More information

Unit-V File operations

Unit-V File operations Unit-V File operations What is stream? C++ IO are based on streams, which are sequence of bytes flowing in and out of the programs. A C++ stream is a flow of data into or out of a program, such as the

More information

Fundamentals of Programming CS-110. Lecture 2

Fundamentals of Programming CS-110. Lecture 2 Fundamentals of Programming CS-110 Lecture 2 Last Lab // Example program #include using namespace std; int main() { cout

More information

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved.

Chapter 2. C++ Basics. Copyright 2014 Pearson Addison-Wesley. All rights reserved. Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style 3 2.1 Variables and Assignments Variables and

More information

Chapter 2. C++ Basics

Chapter 2. C++ Basics Chapter 2 C++ Basics Overview 2.1 Variables and Assignments 2.2 Input and Output 2.3 Data Types and Expressions 2.4 Simple Flow of Control 2.5 Program Style Slide 2-2 2.1 Variables and Assignments Variables

More information

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program

Objectives. Chapter 2: Basic Elements of C++ Introduction. Objectives (cont d.) A C++ Program (cont d.) A C++ Program Objectives Chapter 2: Basic Elements of C++ In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

Lecture 2 Tao Wang 1

Lecture 2 Tao Wang 1 Lecture 2 Tao Wang 1 Objectives In this chapter, you will learn about: Modular programs Programming style Data types Arithmetic operations Variables and declaration statements Common programming errors

More information

Chapter 2: Basic Elements of C++

Chapter 2: Basic Elements of C++ Chapter 2: Basic Elements of C++ Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers in C++ Explore simple data types Discover how a program evaluates

More information

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols.

C++ Basic Elements of COMPUTER PROGRAMMING. Special symbols include: Word symbols. Objectives. Programming. Symbols. Symbols. EEE-117 COMPUTER PROGRAMMING Basic Elements of C++ Objectives General Questions Become familiar with the basic components of a C++ program functions, special symbols, and identifiers Data types Arithmetic

More information

Writing a Good Program. 7. Stream I/O

Writing a Good Program. 7. Stream I/O Writing a Good Program 1 Input and Output I/O implementation is hardware dependent C++ does not, as a part of the language, define how data are sent out and read into the program The input and output (I/O)

More information

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction

Chapter 2: Basic Elements of C++ Objectives. Objectives (cont d.) A C++ Program. Introduction Chapter 2: Basic Elements of C++ C++ Programming: From Problem Analysis to Program Design, Fifth Edition 1 Objectives In this chapter, you will: Become familiar with functions, special symbols, and identifiers

More information

CSCE 206: Structured Programming in C++

CSCE 206: Structured Programming in C++ CSCE 206: Structured Programming in C++ 2017 Spring Exam 2 Monday, March 20, 2017 Total - 100 Points B Instructions: Total of 13 pages, including this cover and the last page. Before starting the exam,

More information

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value

Lecture Notes. System.out.println( Circle radius: + radius + area: + area); radius radius area area value Lecture Notes 1. Comments a. /* */ b. // 2. Program Structures a. public class ComputeArea { public static void main(string[ ] args) { // input radius // compute area algorithm // output area Actions to

More information