Techniques for File I/O

There are a few techniques for file I/O

  1. For example, when data is read from a file, one often needs to know when the end of the file is reached and there is no more data left to be read.

  2. For example, the file may contain numbers which must be read in so that the average can be computed. Suppose the file is open and is connected to the input stream called in_stream. We want to read the numbers from in_stream one at a time, incrementing a counter, and accumulating the numbers to a variable called sum. That can be done as follows:

    double next_number, average, sum = 0.0;
    int count = 0;
    while (in_stream >> next_number)
          {
                sum += next_number;
                count++;
          }
    if (count != 0)
                average = sum / double(count);
    else
                cout << "The file is empty, the average is not computed.\n";

    The above code will work because an expression involving the extraction operator >> is both an action and a Boolean condition. We are familiar with its action, which takes the next number in the input file and assigns it to the variable next_number. This action is carried out if there is a number to be read, and the Boolean expression is satisfied. If there is no more number to be read, the Boolean expression is not satisfied and the action is not carried out.

  3. When reading input from the keyboard, you should prompt for input and echo the input, like this:

    cout << "Enter the number: ";
    cin >> the_number;
    cout << "The number you entered is "<< the_number;

    However if the numbers are read in from a file, then you should not include such prompt lines and echo the input, because there may be no one there to read and respond to what the program sends to the screen. The above 3 lines can be replaced by the following line:

    in_stream >> the_number;

  4. For output to a file, you may also want to send the output separately to the screen, at least when you are debugging the program. Then you don't have to open up the output file with an editor and inspect the content to check if the output looks right. After the program has been debugged, you can then block off (comment out) the lines that send the output to the screen. Screen output is a much slow process compared with the cpu speed, and can significantly slow down your program if you have a lot of output data. You should try to run the logistic map program in my notes to test this out.