Qingquan-Li / blog

My Blog
https://Qingquan-Li.github.io/blog/
132 stars 16 forks source link

C++ File Stream: Member Functions (getline, get, put) for Reading and Writing Files #229

Open Qingquan-Li opened 1 year ago

Qingquan-Li commented 1 year ago

Reference: Book: Starting Out with C++ from Control Structures to Objects, by Tony Gaddis, ninth edition


Concept: File stream objects have member functions for more specialized file reading and writing.


If whitespace characters are part of the data in a file, a problem arises when the file is read by the >> operator. Because the operator considers whitespace characters as delimiters, it does not read them.

For example, consider the file murphy.txt, which contains the following data:

Jayne Murphy
47 Jones Circle
Almond, NC 28702

File contents:

File contents

Use >> operator to read data from the file:

// This program demonstrates how the >> operator should not be used
// to read data that contain whitespace characters from a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string input;     // To hold file input
    fstream nameFile; // File stream object

    // Open the file in input mode.
    nameFile.open("murphy.txt", ios::in);

    // If the file was successfully opened, continue.
    if (nameFile)
    {
        // Read the file contents.
        while (nameFile >> input)
        {
            cout << input;
        }

        // Close the file.
        nameFile.close();
    }
    else
    {
        cout << "ERROR: Cannot open file.\n";
    }
    return 0;
}

Program Output:

JayneMurphy47JonesCircleAlmond,NC28702

1. The getline Member Function

getline function reads a "line" of data, including whitespace characters.

getline(dataFile, str, '\n');
argument explain
dataFile This is the name of the file stream object. It specifies the stream object from which the data is to be read.
str This is the name of a string object. The data read from the file will be stored here.
'\n' This is a delimiter character of your choice. If this delimiter is encountered, it will cause the function to stop reading. (This argument is optional. If it’s left out, '\n' is the default.)

The statement is an instruction to read a line of characters from the file. The function will read until it encounters a \n. The line of characters will be stored in the str object.

// This program uses the getline function to read a line of
// data from the file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string input;      // To hold file input
    fstream nameFile;  // File stream object

    // Open the file in input mode.
    nameFile.open("murphy.txt", ios::in);

    // If the file was successfully opened, continue.
    if (nameFile)
    {
        // Read an item from the file.
        getline(nameFile, input);

        // While the last read operation
        // was successful, continue.
        while (nameFile)
        {
            // Display the last item read.
            cout << input << endl;

            // Read the next item.
            getline(nameFile, input);
        }

        // Close the file.
        nameFile.close();
    }
    else
    {
        cout << "ERROR: Cannot open file.\n";
    }
    return 0;
}

Program Output:

Jayne Murphy
47 Jones Circle
Almond, NC 28702

2. The get Member Function

get function reads a single character from the file.

inFile.get(ch);

A character will be read from the file and stored in ch.

Example: The user is asked for the name of a file. The file is opened and the get function is used in a loop to read the file’s contents, one character at a time.

// This program asks the user for a file name. The file is
// opened and its contents are displayed on the screen.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main()
{
    string fileName;  // To hold the file name
    char ch;          // To hold a character
    fstream file;     // File stream object

    // Get the file name
    cout << "Enter a file name: ";
    cin >> fileName;

    // Open the file.
    file.open(filename, ios::in);

    // If the file was successfully opened, continue.
    if (file)
    {
        // Get a character from the file.
        file.get(ch);

        // While the last read operation was
        // successful, continue.
        while (file)
        {
            // Display the last character read.
            cout << ch;

            // Read the next character
            file.get(ch);
        }

        // Close the file.
        file.close();
    }
    else
        cout << fileName << " could not be opened.\n";
    return 0;
}

This program will display the contents of any file. The get function even reads whitespaces, so all the characters will be shown exactly as they appear in the file.

$ g++ main.cpp -o main
$ ./main
Enter a file name: murphy.txt
Jayne Murphy
47 Jones Circle
Almond, NC 28702

3. The put Member Function

The put member function writes a single character to the file.

outFile.put(ch);
// This program demonstrates the put member function.
#include <iostream>
#include <fstream>
using namespace std;

int main()
{
    char ch;  // To hold a character

    // Open the file for output.
    fstream dataFile("sentence.txt", ios::out);

    cout << "Type a sentence and be sure to end it with a period.\n";

    // Get a sentence from the user one character at a time
    // and write each character to the file.
    cin.get(ch);
    while (ch != '.')
    {
        dataFile.put(ch);
        cin.get(ch);
    }
    dataFile.put(ch); // Write the period.

    // Close the file.
    dataFile.close();
    return 0;
}
$ g++ main.cpp -o main
$ ./main
Type a sentence and be sure to end it with a period.
I am on the way to becoming a great programmer.

Resulting contents of the file

sentence.txt:

I am on the way to becoming a great programmer.