CSCE 2004 - Laboratory Assignment 10

The objective of this laboratory assignment is to give you some experience using file I/O in C++. We will be working with the basic file operations, reading from an input file and writing to an output file, and how to handle EOF (end of file). The assignment has following steps:

  1. Basic File Operations:
  2. First program using files
  3. A simple program demonstrating the use of files in C++ is given below:
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    int main()
    {
            ofstream OutData;
            OutData.open("FirstExample.txt");
            cout << "Hello Dad.\n";
    
            if(!OutData)
            {
                    cerr << "Error: The file could not be opened!\n";
            }
            else
            {
                    OutData << "Hello Mom!!!. This is the first program using the concept of FILES.\n";
                    OutData.close();
            }
            return 0;
    }
    

    Explanation

    We declare a variable, OutData, to be a new output stream. We open it and give the name of the file we want to create, as an argument to the OutData.open function. If the file "FirstExample.txt" already exists, the file will be destroyed and overwritten. If the file could not be created (due, most likely, to a permission problem), an error message will appear on the screen. Wherever we used to use cout we use OutData instead, and the text that is written to the file.

    Running the Program

    Create a file called File.cpp, and use "cut" and "paste" to copy the program above into this file. Use g++ to compile this program. Run it. Now, do an ls on your directory. You should see a new file, FirstExample.txt. Do more FirstExample.txt to confirm that it contains the correct output.

    Running the Program

    Now try to change this program. Instead of writing the above phrase "Hello Mom...", write your first name and last name into the print statement. Run the program and reexamine the contents of FirstExample.txt. Note that it now contains your name instead - the old content has been replaced.

    Cut and paste your modified program below:

  4. Learning about stderr and cerr
  5. There are three standard streams in linux: stdin, stdout, and stderr. cin is the iostream name for stdin, cout for stdout, and cerr for stderr. As we learned in previous labs, you can redirect the standard streams in linux using < for stdin, > for stdout. You can also redirect stderr using 2>. Using &> redirects both stdout and stderr.

    The way that stderr is used is that "normal" output from a program is written to stdout. But, important error messages are written to stderr so that they appear on the screen even when stdout is redirected to a file. Run this program and check that the file has the correct content (i.e., your name) in it and that "Hello Dad" appears on the screen.

    Run the program again, redirecting stdout to a new file, called "Output" by typing:

    ./myprog.exe > Output

    where myprog.exe is whatever you called your executable when you compiled. Look at the contents of Output to confirm that it has the message that used to go to the screen.

    Now we will run your program where you do not have permission to write files.

    cd /bin

    Run the program again, with output to the screen. Since you are in the /bin directory, you need to give the full path.

    ~myusername/2004/labs/lab10/myprog.exe

    Notice that you see an error message because you cannot create your Output file here. However, Hello Dad still appears on the screen. Now, redirect stdout to a new file

    ~myusername/2004/labs/lab10/myprog.exe > ~myusername/2004/labs/lab10/Output2

    Notice that, even though stdout is redirected to a file, the error message still appears on the screen, because it was written to stderr. Finally, cd back to your lab10 directory and confirm that Output2, the message written to stdout, exists.

  6. Making copies of files:
  7. The following program should make a copy of a file. It should read one character at time from the input file and write it to the output file. Copy and paste this program into a file called copyfile.cpp. Compile and run it. You can use any existing ASCII file in your home directory or create one using any simple file editor.

    Note that open and close require character arrays (the C method of handling strings) for the filenames. You can extract a C-style character name from a C++ string by calling Varname.c_str() as was done with the In and Out string parameters inside CopyChar.

    
    #include <iostream>
    #include <fstream>
    using namespace std;
    
    // CopyChar function
    void CopyChar(const string In, const string Out)
    {
       // Declare file stream variables 
       ifstream Din;
       ofstream Dout;
       char Ch;
    
       // Open the input and output files in their respective modes with
       // appropriate error checking.
       Din.open(In.c_str());     // convert from C++ string to C character array
       if (!Din)
          cerr << "Could not open " << In << " for reading.\n";
       else
       {
          Dout.open(Out.c_str());     // convert from C++ string to C character array
          if (!Dout)
             cerr << "Could not open " << Out << " for writing.\n";
          else
          {
             // Read one char at a time from the input file and copy it to output
             // file until we reach end of file.
             while (Din >> Ch)
                Dout << Ch;
             Dout.close();
          }
          Din.close();
       }
    }
    
    // Main program
    int main()
    {
       string InFilename, OutFilename;
    
       // Get the input and output file names.
       cout << "Enter the input file name: ";
       cin >> InFilename;
       cout << "Enter the output file name: ";
       cin >> OutFilename;
    
       // Call the CopyChar function which does the copying.
       CopyChar(InFilename, OutFilename);
       return 0;
    }
    

    Paste OutFilename Below

  8. Modify the above program
  9. Look at the output file produced by your program using more. Notice that all of the spaces have been removed from your input file when you copied characters into the output file. This is because "cin >> variable" always skips white space before reading the variable.

    To fix this, modify the program above to use get instead of >> and put instead of <<. Use the online C++ notes or Google or your book to figure out the syntax of these two functions. Do not ask the TA right away - see what you can find out on your own first.

    Once your new program is working properly, add some code to the CopyChar function to count the number of characters read and return that number to the main program. Then, have the main program output that number to the screen. When you test you program you will now see how many bytes were copied from one file to another.

    Paste Code Below

    Paste Output Below

  10. Reading lines from a file:
  11. Write a new function called "CopyLine" that takes one argument, the input filename, and reads the input file by lines instead of characters and outputs each line to the screen. Call CopyLine from the main program above. Again, make use of online or printed resources to figure out how to use getline to read from a stream. The outline for the new function is given below.

    
    void CopyLine(const string InFilename)
    {
       // Declare a file stream variable.
       // Declare a string variable to hold the line
       // Open your input file for reading with appropriate error checking.
       // loop until EOF
           // Read the input file one line at a time with getline 
           // Write to the screen with cout
       // Close input file.
    }
    

    Submit Work

      This lab assignment will be submitted electronically to the TAs once you fill in the fields below and click on the "submit" button. You do NOT need to print a copy of this document to hand in.

      Your UAID number:
      Your website PASSWORD: