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

Writing Information to Files

The programs you take written then far require the user to reenter data each time the programme runs, because data kept in variables and control properties are stored in RAM and disappears one time the plan stops running. If a programme is to retain data betwixt the times information technology runs, information technology must take a way of saving it. 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 in that location after the program stops running. Data that is stored in a file tin be so retrieved and used at a later time. Programmers unremarkably refer to the process of saving information in a file as writing data to the file. When a piece of data 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 data from the file. When a slice 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 data to files and read data from files. When a file is used by a program, iii steps must exist taken.

  1. Open the file — Opening a file creates a connection betwixt the file and the program. Opening an output file usually creates the file on the disk and allows the program to write data to information technology. Opening an input file allows the programme to read data from the file.
  2. Procedure 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 program is finished using the file, the file must be airtight. Closing a file disconnects the file from the program.

There are ii general ways to admission data stored in a file: sequential access and directly access. When you work with a sequential admission file, you access data from the commencement of the file to the finish of the file. If you want to read a piece of data that is stored at the very terminate of the file, you have to read all of the data that comes before it — y'all cannot leap direct to the desired data. This is similar to the fashion cassette tape players work. If you want to mind to the last vocal on a cassette tape, you have to either fast-forward over all of the songs that come before it or listen to them. There is no way to jump directly to a specific vocal.

When you lot work with a random admission file (besides known as a direct access file), you can jump directly to whatsoever piece of data in the file without reading the information that comes before it. This is like to the way a CD player or an MP3 actor works. You can jump directly to whatever song that you want to listen to.

In order for a program to piece of work with a file on the calculator'south deejay, 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 way for the program to piece of work with that file. It is chosen a "stream" object considering a file tin be idea of as a stream of data.

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

Just equally cin and cout require the iostream file to be included in the programme, C++ file access requires some other 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++ program tin work with a file, it must define an object of i of these data types. The object will be "linked" with an bodily file on the reckoner'southward 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. Table beneath 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 be opened and linked to the file stream object.

The post-obit code shows an example of opening a file for input (reading).

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

The offset statement defines an ifstream object named inputFile. The second statement calls the object'southward open member function, passing the string "Customers.txt" as an argument. In this statement, the open member function opens the Customers.txt file and links it with the inputFile object. Afterward this code executes, you will be able to utilise the inputFile object to read data from the Customers.txt file.

The following code shows an example 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'south open up member office, passing the cord "Employees.txt" as an argument. In this statement, the open member role creates the Employees.txt file and links information technology with the outputFile object. Afterward this code executes, y'all will be able to employ the outputFile object to write data to the Employees.txt file. Information technology's important to remember that when yous call an ofstream object's open up member role, the specified file volition exist created. If the specified file already exists, it will exist erased, and a new file with the same name will exist created.

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

ifstream inputFile("Customers.txt");

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

ofstream outputFile("Employees.txt");

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

  • Most operating systems temporarily store data in a file buffer before it is written to a file. A file buffer is a modest "belongings section" of memory that file-bound data is commencement written to. When the buffer is filled, all the information stored there is written to the file. This technique improves the organization's performance. Closing a file causes any unsaved information that may still exist held in a buffer to be saved to its file. This means the data will be in the file if you demand to read information technology later in the aforementioned program.
  • Some operating systems limit the number of files that may exist open at in one case. When a programme closes files that are no longer being used, it will not deplete more of the operating organization's resource than necessary.

Calling the file stream object's close member part closes a file. Hither is an example:

inputFile.shut();

The programme demonstrates an example that reads strings every bit input from the keyboard and then writes those strings to a file. The plan asks the user to enter the first names of three friends, and so information technology writes those names to a file named Friends.txt. After this code has executed, nosotros tin 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 <cord>
using namespace std;
int main()
{
ofstream outputFile;
string name1, name2, name3;
// Open an outputFile;
outputFile.open("Friends.txt");
// Become the names of 3 friends.
cout << "Enter the names of three friends.\n";
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.\n";
// Close the file
outputFile.close();
return 0;
}

The >> operator not only reads user input from the cin object, just also data from a file. Bold inputFile is an ifstream object, the following statement shows the >> operator reading data from the file into the variable name:

          inputFile >> proper noun;        

Let's await at an example. The program beneath 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 primary()
{
ifstream inputFile;
cord proper noun;
inputFile.open up("Friends.txt");
cout << "Reading data from the file.\n";
inputFile >> name; // Read proper noun one from the line
cout << name << endl; // Display name 1
inputFile >> name; // Read name ii from the line
cout << name << endl; // Display name 2
inputFile >> proper noun; // Read name three from the line
cout << name << endl; // Display proper noun three
inputFile.close(); // Shut the file
render 0;
}

Although some programs employ files to store only pocket-sized amounts of data, files are typically used to hold large collections of data. When a program uses a file to write or read a big amount of data, a loop is typically involved.

Quite often a programme must read the contents of a file without knowing the number of items that are stored in the file. For example, suppose you lot demand to write a programme that displays all of the items in a file, but yous do not know how many items the file contains. You lot tin can open the file then utilise a loop to repeatedly read an item from the file and display it. However, an error will occur if the programme attempts to read across the end of the file. The program needs some way of knowing when the terminate of the file has been reached so information technology will not endeavour to read beyond it.

Fortunately, the >> operator not just reads data from a file, simply too returns a true or false value indicating whether the information was successfully read or not. If the operator returns true, then a value was successfully read. If the operator returns false, it means that no value was read from the file.

In that location is a way to determine whether the open member role successfully opened the file. Afterwards you lot call the open up member part, yous tin exam the file stream object as if it were a Boolean expression.

In each of the previous examples, the proper noun of the file that is opened is difficult-coded as a xi string literal into the program. In many cases, you will want the user to specify the name of a file for the program to open. In C++ xi, you lot tin can pass a string object as an argument to a file stream object's open member function.

The plan below shows an case. This version prompts the user to enter the 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 as an statement to the open part.

kunzeounins.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."

إرسال تعليق

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel