Define an Object Named Infile That Can Be Used to Read Data Into Program Variables From a File.

Writing Data to Files

The programs you have written so far require the user to reenter data each time the program runs, because data kept in variables and control properties are stored in RAM and disappears once the program stops running. If a plan is to retain data between the times it runs, information technology must take a mode of saving information technology. Data is saved in a file, which is usually stored on a computer's disk. Once the data is saved in a file, it will remain at that place after the program stops running. Information that is stored in a file can be so retrieved and used at a subsequently time. Programmers usually refer to the process of saving data in a file as writing data to the file. When a piece of information is written to a file, information technology is copied from a variable in RAM to the file. The process of retrieving data from a file is known as reading information from the file. When a piece of data is read from a file, it is copied from the file into a variable in RAM.

There's three ways to create programs that write information to files and read information from files. When a file is used by a program, iii steps must be taken.

  1. Open the file — Opening a file creates a connection between the file and the program. Opening an output file usually creates the file on the deejay and allows the program to write data to it. Opening an input file allows the plan to read data from the file.
  2. Process the file — Data is either written to the file (if it is an output file) or read from the file (if it is an input file).
  3. Close the file — After the programme is finished using the file, the file must be closed. Endmost a file disconnects the file from the program.

At that place are ii general ways to access data stored in a file: sequential access and direct access. When you work with a sequential access file, you admission data from the beginning of the file to the cease of the file. If y'all want to read a piece of data that is stored at the very terminate of the file, you lot accept to read all of the information that comes before it — you cannot jump directly to the desired data. This is similar to the way cassette tape players work. If you lot desire to listen to the concluding vocal on a cassette tape, you lot take to either fast-frontwards over all of the songs that come up earlier it or listen to them. There is no mode to jump straight to a specific song.

When y'all work with a random access file (likewise known as a direct access file), you tin spring directly to any piece of information in the file without reading the data that comes before it. This is similar to the way a CD actor or an MP3 player works. You lot can jump directly to any vocal that you desire to listen to.

In social club for a program to piece of work with a file on the figurer's disk, the program must create a file stream object in memory. A file stream object is an object that is associated with a specific file and provides a mode for the plan to work with that file. It is chosen a "stream" object because a file can be thought of as a stream of data.

File stream objects work very much similar the cin and cout objects. A stream of information may exist sent to cout, which causes values to be displayed on the screen. A stream of data may be read from the keyboard by cin, and stored in variables. Likewise, streams of information may be sent to a file stream object, which writes the data to a file. When information is read from a file, the data flows from the file stream object that is associated with the file, into variables.

Just as cin and cout require the iostream file to be included in the plan, C++ file admission requires another header file. The file fstream contains all the declarations necessary for file operations. It is included with the following statement:

#include <fstream>

The fstream header file defines the data types ofstream, ifstream, and fstream. Before a C++ plan can work with a file, it must ascertain an object of ane of these data types. The object will be "linked" with an actual file on the estimator's disk, and the operations that may be performed on the file depend on which of these three data types you pick for the file stream object. Tabular array below lists and describes the file stream data types.

Earlier data can be written to or read from a file, the following things must happen:

  • A file stream object must be created
  • The file must exist opened and linked to the file stream object.

The following lawmaking shows an case of opening a file for input (reading).

          ifstream inputFile;
inputFile.open("Customers.txt");

The beginning statement defines an ifstream object named inputFile. The second argument calls the object's open member function, passing the string "Customers.txt" as an statement. In this argument, the open member office opens the Customers.txt file and links it with the inputFile object. Afterwards this lawmaking executes, you will be able to use the inputFile object to read data from the Customers.txt file.

The following lawmaking shows an instance of opening a file for output (writing).

          ofstream outputFile;
outputFile.open("Employees.txt");

The first statement defines an ofstream object named outputFile. The second statement calls the object's open member part, passing the cord "Employees.txt" every bit an argument. In this statement, the open member part creates the Employees.txt file and links information technology with the outputFile object. After this code executes, you volition be able to use the outputFile object to write data to the Employees.txt file. It's important to remember that when you phone call an ofstream object's open member part, the specified file volition be created. If the specified file already exists, it will be erased, and a new file with the same proper name will be created.

It is possible to define a file stream object and open a file in one argument. Here is an example:

ifstream inputFile("Customers.txt");

This statement defines an ifstream object named inputFile and opens the Client.txt file. Here is an example that defines an ofstream object named outputFile and opens the Employees.txt file:

ofstream outputFile("Employees.txt");

The contrary of opening a file is closing it. Although a program's files are automatically closed when the plan shuts down, it is a proficient programming practice to write statements that close them. Hither are two reasons a program should close files when information technology is finished using them:

  • Nearly operating systems temporarily store data in a file buffer before information technology is written to a file. A file buffer is a small "holding section" of retentivity that file-bound data is beginning written to. When the buffer is filled, all the data stored there is written to the file. This technique improves the system'due south functioning. Endmost a file causes any unsaved data that may yet exist held in a buffer to be saved to its file. This ways the data will be in the file if you lot need to read it later in the same programme.
  • Some operating systems limit the number of files that may be open up at one time. When a program closes files that are no longer being used, it will not deplete more of the operating system'southward resources than necessary.

Calling the file stream object's shut member function closes a file. Here is an example:

inputFile.shut();

The programme demonstrates an example that reads strings as input from the keyboard and and so writes those strings to a file. The plan asks the user to enter the first names of three friends, and and so it writes those names to a file named Friends.txt. Later this code has executed, we can open the Friends.txt file using a text editor and look at its contents.

          // This program writes user input to a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int master()
{
ofstream outputFile;
cord name1, name2, name3;
// Open an outputFile;
outputFile.open("Friends.txt");
// Get the names of 3 friends.
cout << "Enter the names of iii friends.\due north";
cout << "Frind #1: ";
cin >> name1;
cout << "Frind #2: ";
cin >> name2;
cout << "Frind #3: ";
cin >> name3;
// Where the names to the file.
outputFile << name1 << endl;
outputFile << name2 << endl;
outputFile << name3 << endl;
cout << "The names were saved to a file.\northward";
// Close the file
outputFile.close();
return 0;
}

The >> operator not only reads user input from the cin object, but likewise data from a file. Assuming inputFile is an ifstream object, the following argument shows the >> operator reading data from the file into the variable proper name:

          inputFile >> name;        

Permit'due south look at an instance. The program below assumes the file Friends.txt exists, opens the file, reads the names and displays them on the screen, and and so closes the file.

          // This program reads data from a file.
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int master()
{
ifstream inputFile;
string name;
inputFile.open("Friends.txt");
cout << "Reading information from the file.\n";
inputFile >> name; // Read name 1 from the line
cout << name << endl; // Display name 1
inputFile >> name; // Read name 2 from the line
cout << proper noun << endl; // Display name ii
inputFile >> name; // Read name 3 from the line
cout << name << endl; // Display proper noun 3
inputFile.close(); // Close the file
return 0;
}

Although some programs utilise files to shop simply small amounts of data, files are typically used to concur big collections of data. When a plan uses a file to write or read a large amount of data, a loop is typically involved.

Quite often a program must read the contents of a file without knowing the number of items that are stored in the file. For instance, suppose y'all demand to write a program that displays all of the items in a file, but yous practise not know how many items the file contains. You can open the file and then use a loop to repeatedly read an item from the file and display it. However, an fault will occur if the program attempts to read beyond the end of the file. The program needs some way of knowing when the stop of the file has been reached and so it will non try to read beyond information technology.

Fortunately, the >> operator non just reads data from a file, merely also returns a truthful or fake value indicating whether the data was successfully read or not. If the operator returns true, then a value was successfully read. If the operator returns fake, it means that no value was read from the file.

There is a fashion to determine whether the open member office successfully opened the file. Subsequently you call the open member office, you can exam the file stream object as if information technology were a Boolean expression.

In each of the previous examples, the name of the file that is opened is hard-coded as a 11 string literal into the program. In many cases, you lot volition want the user to specify the proper noun of a file for the program to open. In C++ 11, you can pass a string object as an statement to a file stream object'southward open member function.

The program beneath shows an example. This version prompts the user to enter the proper name of the file. In line 15, the name that the user enters is stored in a string object named filename. In line 18, the filename object is passed equally an argument to the open office.

brobstthismillond1946.blogspot.com

Source: https://medium.com/@ctchalland/files-b75bb27606e6

0 Response to "Define an Object Named Infile That Can Be Used to Read Data Into Program Variables From a File."

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel