Docsity

Understanding C++ File Streams: Input/Output with ifstream, ofstream, and fstream, Slides of Computer Science

Partial preview of the text

Download Understanding C++ File Streams: Input/Output with ifstream, ofstream, and fstream and more Slides Computer Science in PDF only on Docsity!

Input/Output Streams

File IO

File Streams

  • Provides high level support for file operations in

C++

  • Consists of three components:
    • ifstream - allows only input
    • ofstream - allows only output
    • fstream - allows both input and output

Class Hierarchies

ios

istream ostream

iostream

fstreambase

ifstream ofstream

fstream

File Stream Functions

  • Contains the following functions:
    • open() - opens the stream
    • close() - closes the stream
    • attach() - attaches the stream to file descriptor
    • setbuf() - set the stream buffer
    • rdbuf() - returns the pointer to stream buffer
    • str() - returns a pointer to the buffer array

File Processing Modes

  • nMode can be any of the following:
  • ios::in - input processing
  • ios::out - output processing
  • ios::trunc - discard the file contents
  • ios::nocreate - the file must exist in order to write
  • ios::noreplace - cannot rewrite to an existing file
  • ios::binay - open the file in binary mode
  • ios::app - append the new data to the contents of the file
  • ios::ate - open the file for output and move to the end
  • ios::in|ios::out - both input and output

File Protection Modes

  • nProt can be one of the following:
    • filbuf::shcompat - compatibility share mode
    • filebuf::sh_none - no sharing
    • filebuf::sh_read - read sharing
    • filebuf::sh_write - write sharing
    • filebuf::sh_read|filebuf::sh_write - both read and write sharing

File Streams - open()

  • Opens a file as a stream
  • Syntax

void open(const char *sfile, int nMode, int nProt =

  • Usage

fstream my_file; my_file.open(“cs265.txt”, ios::out);

File Streams - close()

  • Close the opened file.
  • The stream’s error flag is cleared unless the close fails.
  • Syntax

void close()

  • Usage

my_file.close();

File I/O – Example contd…

  • //Until the end of file is reached, read from //the file and write it to the out file and echo on the screen. while(fIn.get(cCh)) { fOut.put(cCh); cout.put(cCh); //echo on terminal ++nCnt; }
  • //Write the final byte count cout << "[ " << nCnt << " ]" << endl; fOut << nCnt;
  • //Close the files fIn.close(); fOut.close();
  • return 0;}

File I/O - Files

  • copy.in

abcd efg hi j

  • copy.out

abcd efg hi j 14