Loading....
Coupon Accepted Successfully!

 

Steps Of File Operations

Before performing file operations, it is necessary to create a file. The operation of a file involves the following basic activities:
  • File name
  • Opening the file
  • Reading or writing the file (file processing)
  • Detecting errors
  • Closing the file
The file name can be a sequence of characters, called a string. Strings are always declared with a character array. Using the file name, a file is recognized. The length of the file name depends on the operating system; for example, WINDOWS-98 supports long file names, whereas MS-DOS supports only eight characters. A file name also contains an extension of three characters. The file name should not be a device name such as LPT1 and CON. The list of device names is given in Table. You might have observed the .cpp extension to the C++ program file name separated by the dot (.). The extension is optional. The following file names are valid in MS-DOS and WINDOWS-98 operating systems:
 

data.dbf // extension is .dbf

tc.exe // extension is .exe

prg.cpp // extension is .cpp

prg.exe // extension is .exe

prg.obj // extension is .obj

Marks // without extension

 
The first step in the disk file I/O operation is the creation of a file stream object and connecting it with the file name. The classes ifstream, ofstream, and fstream can be used for creating a file stream defined in the header file fstream.h. The selection of the class is according to the operation that is to be carried out with the file. The operation may be read or write. Two methods are used for the opening of a file. They are as follows:
 

(a) Constructor of the class

(b) Member function open()

  1. Constructor of the class
     
    When objects are created, a constructor is automatically executed, and objects are initialized. In the same way, the file stream object is created using a suitable class, and it is initialized with the file name. The constructor itself uses the file name as the fist argument and opens the file. The class ofstream creates output stream objects, and the class ifstream creates input stream objects.
Consider the following examples:
 

(a) ofstream out (“text”);

(b) ifstream in (“list”);

 
In the statement (a), out is an object of the class ofstream; file name text is opened, and data can be written to this file. The file name text is connected with the object out. Similarly, in the statement (b), in is an object of the class ifstream. The file list is opened for input and connected with the object in. It is also valid to use a similar name for input and output operations.
 
It is possible to use these file objects in program statements such as stream objects. Consider the following statements:
 
cout<<“One Two Three”;
 
The above statement displays the given string on the screen.
 
out<<“One Two Three”;
 
The above statement writes the specified string into the file pointed by the object out as shown in Figure. The insertion operator << has been overloaded appropriately in the ostream class to write data to the appropriate stream.
 
Fig: Interaction between fstream object and disk file
 
Consider the following statements:
 
 
In the last statement, we have separated each value using an “endl” manipulator. It is essential, because when we store values such as 15 and 123.34, they are stored in the file as strings; that is, 123.34 would be stored as ‘1’,‘2’,‘3’,‘.’, ‘3’,‘4’.
 
The value 123.34 requires four bytes, but when stored in a file, it occupies six bytes. When we need to store more numeric values, more bytes are occupied and the file size is increased. Every data item should be separated by a delimiter. This is essential, because during the read operation, the extraction operator cannot determine where one number is ending and another is beginning. A similar problem can be observed while reading strings. The above limitation can be overcome using the binary file operation that is discussed later in the same chapter.
 
Similarly, in the following statements,
 

in>>string; // Reads string from the file where string is a character array

in>>num; // Reads number from the file where num is an integer variable

 
the in object reads data from the file associated with it, as shown in Figure. For reading data from a file, we have to create an object of the ifstream class. The new line character (“\n”) inserted at the end of every line helps the overloaded operator separate the various items stored in the file. When numbers are read back from the file, they are converted into their binary format.
 
Fig: Interaction between ifstream object and disk file
 

16.1 Write a program to open an output file using fstream class.

#include<fstream.h> //File I/O

#include<conio.h>

int main()

{

clrscr();

ofstream out(“text”);

out <<“One Two Three Four\n”;

out << “1 2 3 4”;

out <<“\n** The End **”;

return 0;

}

 
Explanation: In the above program, the statement ofstream out (“text”) text is opened and connected with the object out.
 

Use of object out

out <<“One Two Three Four \n”;

out <<“1 2 3 4”;

out <<“\n** The End **”;

 
The above statements write data (enclosed in quotation marks) to the file pointed by the object out, that is, text. The operator << is an insertion operator, and it writes the data in the file named text. To open the file text, the user can use Turbo C++ editor and click DOS Shellof the file menu. On DOS, the prompt user should type the file name and press the enter key. In addition, a further editor can be opened from the DOS prompt, and the user can see the contents of the text file. The contents of the file can be seen by the user, and it appears as follows:
 

Contents of the file text

One Two Three Four

1 2 3 4

** The End **

 
While opening a file for the writing operation, the user should give the new file name. If the given file already exists, its contents are erased and it is treated as a new file.
 

16.2 Write a program to read data from file using object of ifstream class.

#include<fstream.h>

#include<conio.h>

int main()

{

clrscr();

char *n;

ifstream in(“text”); // Opens a file in read mode

in >>n; // Reads string from file

cout<<n <<“”; // Displays string to the console

in >>n ;

cout<<n <<“”;

in >>n ;

cout<<n <<“”;

return 0;

}

OUTPUT

One Two Three

 
Explanation: In the above program, the statement ifstream in (“text”); is opened and connected with the object in. The statement in >>n reads data from the file and assigns it to the variable followed by the (>>) extraction operator. Here, the variable *n is a character pointer. If a numeric value is read using character type, the data cannot be used for arithmetic operations. If character-type data are read using a numeric-type variable, ASCII values of the character read will be displayed. Hence, the variable type should match with the data type. The statement cout<<n <<“ ”; displays the data stored in variable n.
 
In the above programs, the file associated with the object are automatically closed when the stream object goes out of scope. In order to explicitly close the file, the following statement is used:
 

Closing of files

out.close();

in.close();

 
Here, out is an object, and close() is a member function that closes the file connected with the object out. Similarly, the file associated with the object in is closed by the member function close().
 

16.3 Write a program to write and read text in a file. Use ofstream and ifstream classes.

#include<fstream.h>

#include<conio.h>

int main()

{

clrscr();

char name[15];

int age;

ofstream out(“text”);

cout<<“\n Name:”;

cin>>name;

cout<<“Age:”;

cin>>age;

out<<name<<“\t”;

out<<age <<“\n”;

out.close(); // File is closed

ifstream in (“text”);

in>>name;

in>>age;

cout<<“\nName\t:”<<name<<“\n”;

cout<<“Age:”<<age;

in.close();

return 0;

}

OUTPUT

Name : Sameer

Age : 24

Name : Sameer

Age : 24

 
Explanation: The above program is a combination of the previous two programs. The out is an object of the ofstream class, and it is linked with the output file text. The data entered by the user is written in the file text. The close() function closes the file associated with the object out. Again, the same file is opened by the in object of class ifstream for reading purpose. The data recently written are read and displayed on the screen. Thus, in a program, both write and read operations are performed. The use of functionclose() is essential for changing the mode of the file. In case a file is not closed and an attempt is again made to open it in another mode, no compile time error is generated. However, the result will not be satisfactory.
  1. The open() function
     
    In the last few programs, we have studied how files could be opened for reading and writing using constructors. Now, the second approach can be used with the open() function. The open() function is used to open a file, and it uses the stream object. The open() function has two arguments. First is the file name, and second is the mode. The mode specifies the purpose of opening a file; that is, read, write, append, and so on. The details are discussed in heading. In the following examples, the default mode is considered. The default values for ifstream is (ios::in) reading only and for fstream is (ios::out) writing only.

 

16.4 Write a program to open multiple files for writing and reading purposes. Use open() function.

#include<fstream.h>

#include<conio.h>

int main()

{

clrscr();

ofstream out;

// Writing data //

out.open (“months”); // Opens file

out<<“March\n”; // Writes string to the f ile

out<<“April\n”;

out <<“June\n”;

out.close(); // Closes the file

out.open (“days”); // Opens another file

out <<“31\n”;

out <<“30\n”;

out <<“30\n”;

out.close(); // closes the file

// reading data //

#define T 20

char text[T];

ifstream in;

in.open (“months”); // opens file for reading

cout<<“\nMonth Names \n”;

while (in)

{

in.getline(text,T);

cout<<text<<“\n”;

}

in.close();

in.open (“days”);

cout<<“\nDays \n”;

while (in)

{

in.getline(text,T);

cout<<text<<“\n”;

}

in.close();

return 0;

}

OUTPUT

Month Names

March

April

June

Days

31

30

30

 
Explanation: In the above program, out is an object of the ofstream class. The object out is used with the open() function to open files for the write operation. Two files are opened: months and days. Month names are written in the file months, and number of days is written in the file days. The data are written in the files one after another. The same object is used for both the files; hence, it is necessary to close a previously linked file with the object before opening a new file. In this program, the month file is opened first and after closing it, the file days is opened. The files are closed using the function close(). The same procedure is implemented for opening the same files for the reading purpose. When the end of the file is reached, the while loop terminates.
 
Fig: Stream objects with multiple files
 
As shown in Figure, the out object opens the month and days file one after another for writing. The object in opens these files for reading. Before opening the next file, the previously associated file with the object is closed. A single object cannot open multiple files simultaneously.




Test Your Skills Now!
Take a Quiz now
Reviewer Name