CSCI 1300
Lecture Notes


10/16/97

Administrative Stuff 



Administrative Stuff

  • Project proposals

  • Projects

  • Graphics



    Files

    What is a file?

  • Files are logical units of information in secondary storage (disk, tape, etc..)

  • A file may consist of one or more disk or tape blocks of storage

  • Files may be created, written, modified, appended, read, and deleted.

  • Files can contain ASCII data, numeric data, or any combination thereof.

  • Unlike information stored in memory, information stored in files is persistent.


    Fstreams

  • Fstreams are objects that represent files

  • Fstreams are defined in fstream.h

  • To create an object to be used to access a file, declare an object of type fstream, like this:

    fstream outputfile;
  • fstreams support the following operations:
  • open() - associate a file with the fstream object.

  • close() - terminate connection between file and fstream object.

  • eof() - a boolean function that returns true if the last input operation failed because the end of the file has been reached, false otherwise.

  • << - an operator that outputs an object to a file.

  • >> - an operator that inputs an object from a file.

  • fail() - returns true if the last operation on that fstream failed, false otherwise

  • get() - reads one character at a time (including white space)

  • seekg(), tellg() - set and read position in an input stream

  • seekp(), tellp() - set and read position in an output stream


  • Opening a file

  • Files are accessed in C++ using fstreams.

  • First we declare an fstream object, then we open it for reading or writing

  • Files are opened by calling the open() member function for the fstream object.

  • The open member function takes two parameters, the file name and the mode.

  • Possible modes: ios::in, ios::out, ios::app

  • Examples:

    outputfile.open("scotts_output", ios::out);

    outputfile2.open("logfile", ios::app);

    inputfile.open("data_file", ios::in);

  • Fstreams opened for reading may not be written to, fstreams opened for writing (or appending) may not be read from.


    Reading and writing files

  • Once the file is opened, we can access the information using >> and << just like cin and cout.

  • Example:
    outputfile << "This is a test\n";

    outputfile << x << " + " << y << " = " << x + y << endl;

    inputfile >> name;

  • eof() is used to tell that we have read past the end of the file.

  • Example:
    inputfile >> name;
    if(inputfile.eof() = = TRUE) {
      cout << "no more names\n";
    }


    Closing files

  • To disconnect a fstream object from the file, use the close() function.

  • Examples:
    outputfile.close();
    inputfile.close();
  • In general, it is a good idea to close a file as soon as you are finished with it.

  • If you don't close the files, they will be closed when the program ends.


    Example: A program to count the characters, words, and lines in a file.