Đang chuẩn bị nút TẢI XUỐNG, xin hãy chờ
Tải xuống
Absolute C++ (4th Edition) part 51. KEY BENEFIT: C++ programming concepts and techniques are presented in a straightforward style using understandable language and code. KEY TOPICS: C++ Basics; Flow of Control; Function Basics; Parameters and Overloading; Arrays; Structures and Classes; Constructors; Operator Overloading, Friends, and References; Strings; Pointers and Dynamic Arrays; Separate Compilation and Namespaces; Streams and File I/O; Recursion; Inheritance; Polymorphism and Virtual Functions; Templates; Linked Data Structures; Exception Handling; Standard Template Library; Patterns and UML. MARKET: Useful for both beginning and intermediate C++ programmers. . | I O Streams 507 Display 12.2 Appending to a File 1 Appends data to the end of the file alldata.txt. 2 include fstream 3 include iostream 4 using std ofstream 5 6 using std cout using std ios 7 int main 8 9 cout Opening data.txt for appending. n 10 ofstream fout 11 fout.open data.txt ios app 12 fout 5 6 pick up sticks. n 13 7 8 ain t C great n 14 fout.close 15 cout End of appending to file. n 16 return 0 17 Sample Dialogue data.txt Before program is run 1 2 bucket my shoe. 3 4 shut the door. data.txt Afterprogram is run 1 2 bucket my shoe. 3 4 shut the door. 5 6 pick up sticks. 7 8 ain t C great Screen Output Opening data.txt for appending. End of appending to file. 508 Streams and File I O Appending to a File If you want to append data to a file so that it goes after any existing contents of the file open the file as follows. Syntax Output_Stream .open F e_Name ios app Example ofstream outStream outStream.openCimportant.txt ios app Tip Another Syntax for Opening a File Each of the classes ifstream and ofstream has constructors that allow you to specify a file name and sometimes other parameters for opening a file. A few examples will make the syntax clear. The two statements ifstream inStream inStream.openCinfile.txt can be replaced by the following equivalent line ifstream inStream infile.txt The two statements ofstream outStream outStream.openCoutfile.txt can be replaced by the following equivalent line ofstream outStreamCoutfile.txt As our final example the two lines ofstream outStream outStream.openCimportant.txt ios app are equivalent to the following ofstream outStreamCimportant.txt ios app I O Streams 509 Tip Check That a File Was Opened Successfully A call to open can be unsuccessful for a number of reasons. For example if you try to open an input file and there is no file with the external name that you specified then the call to open will fail. As another example an attempt to open an output file could fail because the file exists and your program that is