Chapter 17 C Files n n n By

Chapter 17 C++ Files n n n By C. Shing ITEC Dept Radford University

Objectives n n Understand how to use files by file streams Understand how to use file member functions 2

Access File by File Stream n File stream: n n Input file stream: ifstream is inherited from istream Example: ifstream infile; output file stream: ofstream is inherited from ostream Example: ofstream outfile; 3

File Member Function - open Open file: n n Form: filestream. open (“filename”) Or filestream. open (“filename”, permission) Permission: 1. Input: read ios: : in 2. Output: erase write ios: : out 3. Append: ios: : app 4

File Member Function – open (Cont. ) n Open file: (Cont. ) n n Starts from beginning of the file Need to check successful when use member function fail() 5

File Member Function – open (Cont. ) n Open file: (Cont. ) Example: infile. open (“/usr/include/stdio. h”); or outfile. open (“current_dir_file”); or outfile. open (argv[1]); 6

File Member Function - fail Form: filestream. fail () Returns true if open is not successful n Example: if (infile. fail()) cout << “Cannot open input file. n”; 7

File Member Function – seekp n Move pointer to any place of the file: seekp n Form: filestream. seekp (offset); n Offset: relative to the current position n n -: to previous +: to next Example: infile. seekp (0); // go to the beginning of the file 8

File Member Function – eof n check the end of file: returns true if reach to end of file n Form: filestream. eof (); Example: char c; … while (!infile. eof ()) { infile>>c; outfile<<c; } 9

File Member Function - close Form: infile. close (); Example: infile. close(); outfile. close(); n 10

File Member Function (Cont. ) n Example: cmdprompt. cpp 11

File Member Function (Cont. ) n Example: sparse. c sparse. txt normal. txt 12

References Deitel & Deitel: C++ How to Program, 4 th ed. , Chapter 14, Prentice Hall n 13
- Slides: 13