Saturday, 2 February 2013

file formation in c++



  • ofstream: Stream class to write on files
  • ifstream: Stream class to read from files
  • fstream: Stream class to both read and write from/to files.

These classes are derived directly or indirectly from the classes istream, and ostream. We have already used objects whose types were these classes: cin is an object of class istream and cout is an object of class ostream. Therefore, we have already been using classes that are related to our file streams. And in fact, we can use our file streams the same way we are already used to use cin and cout, with the only difference that we have to associate these streams with physical files. Let's see an example:

1
2
3
4
5
6
7
8
9
10
11
12
// basic file operations
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile;
  myfile.open ("example.txt");
  myfile << "Writing this to a file.\n";
  myfile.close();
  return 0;
}
[file example.txt]
Writing this to a file.


This code creates a file called example.txt and inserts a sentence into it in the same way we are used to do withcout, but using the file stream myfile instead.

But let's go step by step:

Open a file


The first operation generally performed on an object of one of these classes is to associate it to a real file. This procedure is known as to open a file. An open file is represented within a program by a stream object (an instantiation of one of these classes, in the previous example this was myfile) and any input or output operation performed on this stream object will be applied to the physical file associated to it.

In order to open a file with a stream object we use its member function open():

open (filename, mode);
Where filename is a null-terminated character sequence of type const char * (the same type that string literals have) representing the name of the file to be opened, and mode is an optional parameter with a combination of the following flags:

ios::inOpen for input operations.
ios::outOpen for output operations.
ios::binaryOpen in binary mode.
ios::ateSet the initial position at the end of the file.
If this flag is not set to any value, the initial position is the beginning of the file.
ios::appAll output operations are performed at the end of the file, appending the content to the current content of the file. This flag can only be used in streams open for output-only operations.
ios::truncIf the file opened for output operations already existed before, its previous content is deleted and replaced by the new one.

All these flags can be combined using the bitwise operator OR (|). For example, if we want to open the fileexample.bin in binary mode to add data we could do it by the following call to member function open():

1
2
ofstream myfile;
myfile.open ("example.bin", ios::out | ios::app | ios::binary); 


Each one of the open() member functions of the classes ofstreamifstream and fstream has a default mode that is used if the file is opened without a second argument:

classdefault mode parameter
ofstreamios::out
ifstreamios::in
fstreamios::in | ios::out

For ifstream and ofstream classes, ios::in and ios::out are automatically and respectively assumed, even if a mode that does not include them is passed as second argument to the open() member function.

The default value is only applied if the function is called without specifying any value for the mode parameter. If the function is called with any value in that parameter the default mode is overridden, not combined.

File streams opened in binary mode perform input and output operations independently of any format considerations. Non-binary files are known as text files, and some translations may occur due to formatting of some special characters (like newline and carriage return characters).

Since the first task that is performed on a file stream object is generally to open a file, these three classes include a constructor that automatically calls the open() member function and has the exact same parameters as this member. Therefore, we could also have declared the previous myfile object and conducted the same opening operation in our previous example by writing:

 
ofstream myfile ("example.bin", ios::out | ios::app | ios::binary);


Combining object construction and stream opening in a single statement. Both forms to open a file are valid and equivalent.

To check if a file stream was successful opening a file, you can do it by calling to member is_open() with no arguments. This member function returns a bool value of true in the case that indeed the stream object is associated with an open file, or false otherwise:

 
if (myfile.is_open()) { /* ok, proceed with output */ }


Closing a file

When we are finished with our input and output operations on a file we shall close it so that its resources become available again. In order to do that we have to call the stream's member function close(). This member function takes no parameters, and what it does is to flush the associated buffers and close the file:

 
myfile.close();


Once this member function is called, the stream object can be used to open another file, and the file is available again to be opened by other processes.

In case that an object is destructed while still associated with an open file, the destructor automatically calls the member function close().

Text files

Text file streams are those where we do not include the ios::binary flag in their opening mode. These files are designed to store text and thus all values that we input or output from/to them can suffer some formatting transformations, which do not necessarily correspond to their literal binary value.

Data output operations on text files are performed in the same way we operated with cout:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// writing on a text file
#include <iostream>
#include <fstream>
using namespace std;

int main () {
  ofstream myfile ("example.txt");
  if (myfile.is_open())
  {
    myfile << "This is a line.\n";
    myfile << "This is another line.\n";
    myfile.close();
  }
  else cout << "Unable to open file";
  return 0;
}
[file example.txt]
This is a line.
This is another line.


Data input from a file can also be performed in the same way that we did with cin:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
// reading a text file
#include <iostream>
#include <fstream>
#include <string>
using namespace std;

int main () {
  string line;
  ifstream myfile ("example.txt");
  if (myfile.is_open())
  {
    while ( myfile.good() )
    {
      getline (myfile,line);
      cout << line << endl;
    }
    myfile.close();
  }

  else cout << "Unable to open file"; 

  return 0;
}
This is a line.
This is another line.  


This last example reads a text file and prints out its content on the screen. Notice how we have used a new member function, called good() that returns true in the case that the stream is ready for input/output operations. We have created a while loop that finishes when indeed myfile.good() is no longer true, which will happen either if the end of the file has been reached or if some other error occurred.

Checking state flags

In addition to good(), which checks whether the stream is ready for input/output operations, other member functions exist to check for specific states of a stream (all of them return a bool value): 

bad()
Returns true if a reading or writing operation fails. For example in the case that we try to write to a file that is not open for writing or if the device where we try to write has no space left.
fail()
Returns true in the same cases as bad(), but also in the case that a format error happens, like when an alphabetical character is extracted when we are trying to read an integer number.
eof()
Returns true if a file open for reading has reached the end.
good()
It is the most generic state flag: it returns false in the same cases in which calling any of the previous functions would return true.

In order to reset the state flags checked by any of these member functions we have just seen we can use the member function clear(), which takes no parameters.

Saving a File
One of the operations you can perform on a file consists of saving it, which is equivalent to storing its value(s) to a medium. To save a file, you can first declare an instance of theofstream class using one of its constructors from the following syntaxes:
ofstream();

ofstream(const char* FileName, int FileMode);
The default constructor allows you to initiate file processing without giving details. If you decide to use the default constructor, you can then call one of the methods we will see to perform the necessary operation. 
The ofstream(const char* FileName, int FileMode) constructor provides a complete mechanism for creating a file. It does this with the help of its two arguments. The first argument, FileName, is a string that specifies the name of the file that needs to be saved. The second argument, FileMode, specifies the kind of operation you want to perform on the file. It can be one of the modes we listed above.
Once you have decided what you want to do with a file, you use the << operator to save each value. Here is an example:

#include <fstream>

#include <iostream>

using namespace std;



int main()

{

    char FirstName[30], LastName[30];

    int Age;

    char FileName[20];



    cout << "Enter First Name: ";

    cin >> FirstName;

    cout << "Enter Last Name:  ";

    cin >> LastName;

    cout << "Enter Age:        ";

    cin >> Age;



    cout << "\nEnter the name of the file you want to create: ";

    cin >> FileName;

    ofstream Students(FileName, ios::out);

    Students << FirstName << "\n" << LastName << "\n" << Age;



    cout << "\n\n";

    return 0;

}
If you had used the default constructor to declare an ofstream variable, you can call theopen() method to actually process the file. The syntax of the open method is:
void open(const char* FileName, int Mode, int nProt = filebuf::openprot );
This method behaves exactly like, and uses the same arguments as, the constructor we described above. The first argument represents the name of the file you are dealing with and the FileMode argument follows the modes of the above table.

Because the fstream class in this case is declared as ofstream, the compiler is aware that you want to save a file (in reality, the use of ofstream means that you want to write to a file, in other words you want the FileMode with a value of ios::out), you can use the second constructor with just the FileName as argument or you can call the open() method with only the name of the file.
After using a file, you should close it. This is taken care by using the ofstream::close()method whose syntax is:
void close();

Opening a File
Besides saving, another operation you can perform consists of opening an already existing file to have access to its contents. To do this, C++ provides the ifstream class. Like ofstream, the ifstream class provides various constructors you can use, two of which are particularly important. If you have enough information about the file you want to open, you can use the following constructor:
ifstream(const char* FileName, int FileMode);
The first argument of the constructor, FileName, is a constant string that represents the file that you want to open. The FileMode argument is a natural number that follows the table of modes as we described above.
If necessary, you can also declare an empty instance of the ifstream class using the default constructor:
ifstream();
After declaring this constructor, you can use the ifstream::open() method to formally open the intended file. The syntax of the open() method is:
open(const char* FileName, int FileMode);
This method uses the same arguments as the above constructor. By default, when declaring an instance of the ifstream class, it is assumed that you want to open a file; that is, you want to use the FileMode attribute with a value of ios::in. Therefore, the second argument is already set to ios::in value. This allows you to call the open() method with just the FileName value.

After using the ifstream class, you can close it using the ifstream::close() method. Here is an example:
#include <fstream>

#include <iostream>

using namespace std;



int main()

{

    char FirstName[30], LastName[30];

    int Age;

    char FileName[20];

/*

    cout << "Enter First Name: ";

    cin >> FirstName;

    cout << "Enter Last Name:  ";

    cin >> LastName;

    cout << "Enter Age:        ";

    cin >> Age;



    cout << "\nEnter the name of the file you want to create: ";

    cin >> FileName;

    ofstream Students(FileName, ios::out);

    Students << FirstName << "\n" << LastName << "\n" << Age;

*/

    cout << "Enter the name of the file you want to open: ";

    cin >> FileName;

    ifstream Students(FileName);

    Students >> FirstName >> LastName >> Age;



 cout << "\nFirst Name: " << FirstName;

    cout << "\nLast Name:  " << LastName;

    cout << "\nEnter Age:  " << Age;



    cout << "\n\n";

    return 0;

}

No comments:

Post a Comment