tailieunhanh - A Complete Guide to Programming in C++ part 67

A Complete Guide to Programming in C++ part 67. This book provides both novice and experienced programmers with a comprehensive resource manual for the C++ programming language. Readers gain experience in all aspects of programming, from elementary language concepts to professional software development, with in depth coverage of all the language elements en route. These elements are carefully ordered to help the reader create useful programs every step of the way. | OPENING A FILE FOR RANDOM ACCESS 639 Random File Access So far we have only looked at sequential file access. If you need access to specific information in such a file you have to walk through the file from top to tail and new records are always appended at the end of the file. Random file access gives you the option of reading and writing information directly at a pre-defined position. To be able to do this you need to change the current file position explicitly that is you need to point the get put pointer to the next byte to be manipulated. After pointing the pointer you can revert to using the read and write operations that you are already familiar with. Open Modes One prerequisite of random file access is that the position of the records in the file can be precisely identified. This implies opening the file in binary mode to avoid having to transfer additional escape characters to the file. Example ios openmode mode ios in ios out ios app ios binary fstream fstr mode This statement opens the file in binary mode for reading and appending at end-of-file. The file will be created if it did not previously exist. Random read access to the file is possible but for write operations new records will be appended at the end of the file. To enable random read and write access to a file the file can be opened as follows Example ios openmode mode ios in ios out ios binary fstream fstr mode However this technique can only be used for existing files. If the file does not exist you can use the ios trunc flag to create it. The section File State discusses your error handling options if a file such as cannot be found. 640 CHAPTER 29 MORE ABOUT FILES POSITIONING FOR RANDOM ACCESS The three access points in a file Access point Positioning flag File Beginning of the file ios beg Current position ios cur End of file ios end POSITIONING FOR RANDOM ACCESS 641 Discovering and Changing the Current Position The file stream classes comprise

TỪ KHÓA LIÊN QUAN