C++ Files and Streams
C++ Files and Streams
So far, we have been using the iostream standard library, which provides cin and cout methods for reading from standard input and writing to standard output respectively.
This tutorial will teach you how to read and write from a file. This requires another standard C++ library called fstream, which defines three new data types −
Sr.No | Data Type & Description |
---|---|
1 |
ofstream
This data type represents the output file stream and is used to create files and to write information to files.
|
2 |
ifstream
This data type represents the input file stream and is used to read information from files.
|
3 |
fstream
This data type represents the file stream generally, and has the capabilities of both ofstream and ifstream which means it can create files, write information to files, and read information from files.
|
To perform file processing in C++, header files <iostream> and <fstream> must be included in your C++ source file.
Opening a File
A file must be opened before you can read from it or write to it. Either ofstream or fstream object may be used to open a file for writing. And ifstream object is used to open a file for reading purpose only.
Following is the standard syntax for open() function, which is a member of fstream, ifstream, and ofstream objects.
void open(const char *filename, ios::openmode mode);
Here, the first argument specifies the name and location of the file to be opened and the second argument of the open()member function defines the mode in which the file should be opened.
Sr.No | Mode Flag & Description |
---|---|
1 |
ios::app
Append mode. All output to that file to be appended to the end.
|
2 |
ios::ate
Open a file for output and move the read/write control to the end of the file.
|
3 |
ios::in
Open a file for reading.
|
4 |
ios::out
Open a file for writing.
|
5 |
ios::trunc
If the file already exists, its contents will be truncated before opening the file.
|
You can combine two or more of these values by ORing them together. For example if you want to open a file in write mode and want to truncate it in case that already exists, following will be the syntax −
ofstream outfile; outfile.open("file.dat", ios::out | ios::trunc );
Similar way, you can open a file for reading and writing purpose as follows −
fstream afile; afile.open("file.dat", ios::out | ios::in );
Closing a File
When a C++ program terminates it automatically flushes all the streams, release all the allocated memory and close all the opened files. But it is always a good practice that a programmer should close all the opened files before program termination.
Following is the standard syntax for close() function, which is a member of fstream, ifstream, and ofstream objects.
void close();
Writing to a File
While doing C++ programming, you write information to a file from your program using the stream insertion operator (<<) just as you use that operator to output information to the screen. The only difference is that you use an ofstream or fstreamobject instead of the cout object.
Reading from a File
You read information from a file into your program using the stream extraction operator (>>) just as you use that operator to input information from the keyboard. The only difference is that you use an ifstream or fstream object instead of the cinobject.
Read and Write Example
Following is the C++ program which opens a file in reading and writing mode. After writing information entered by the user to a file named afile.dat, the program reads information from the file and outputs it onto the screen −
#include <fstream> #include <iostream> using namespace std; int main () { char data[100]; // open a file in write mode. ofstream outfile; outfile.open("afile.dat"); cout << "Writing to the file" << endl; cout << "Enter your name: "; cin.getline(data, 100); // write inputted data into the file. outfile << data << endl; cout << "Enter your age: "; cin >> data; cin.ignore(); // again write inputted data into the file. outfile << data << endl; // close the opened file. outfile.close(); // open a file in read mode. ifstream infile; infile.open("afile.dat"); cout << "Reading from the file" << endl; infile >> data; // write the data at the screen. cout << data << endl; // again read the data from the file and display it. infile >> data; cout << data << endl; // close the opened file. infile.close(); return 0; }
When the above code is compiled and executed, it produces the following sample input and output −
$./a.out Writing to the file Enter your name: Zara Enter your age: 9 Reading from the file Zara 9
Above examples make use of additional functions from cin object, like getline() function to read the line from outside and ignore() function to ignore the extra characters left by previous read statement.
File Position Pointers
Both istream and ostream provide member functions for repositioning the file-position pointer. These member functions are seekg ("seek get") for istream and seekp ("seek put") for ostream.
The argument to seekg and seekp normally is a long integer. A second argument can be specified to indicate the seek direction. The seek direction can be ios::beg (the default) for positioning relative to the beginning of a stream, ios::cur for positioning relative to the current position in a stream or ios::end for positioning relative to the end of a stream.
The file-position pointer is an integer value that specifies the location in the file as a number of bytes from the file's starting location. Some examples of positioning the "get" file-position pointer are −
// position to the nth byte of fileObject (assumes ios::beg) fileObject.seekg( n ); // position n bytes forward in fileObject fileObject.seekg( n, ios::cur ); // position n bytes back from end of fileObject fileObject.seekg( n, ios::end ); // position at end of fileObject fileObject.seekg( 0, ios::end );
C++ Manipulators - endl, setw, setprecision, setf
Formatting output using manipulators
Formatted output is very important in development field for easily read and understand.
C++ offers the several input/output manipulators for formatting, commonly used manipulators are given below..
Manipulator | Declaration in |
endl | iostream.h |
setw | iomanip.h |
setprecision | iomanip.h |
setf | iomanip.h |
endl
endl manipulator is used to Terminate a line and flushes the buffer.
Difference b/w '\n' and endl
When writing output in C++,you can use either std::endl or '\n' to produce a newline, but each has a different effect.
- std::endl sends a newline character '\n' and flushes the output buffer.
- '\n' sends the newline character, but does not flush the output buffer.
The distinction is very important if you're writing debugging messages that you really need to see immediately, you should always use std::endl rather than '\n' to force the flush to take place immediately.
The following is an example of how to use both versions, although you cannot see the flushing occuring in this example.
#include <iostream.h> int main() { cout<<"USING '\\n' ...\n"; cout<<"Line 1 \nLine 2 \nLine 3 \n"; cout<<"USING end ..."<< endl; cout<< "Line 1" << endl << "Line 2" << endl << "Line 3" << endl; return 0; }
Output
USING '\n' ... Line 1 Line 2 Line 3 USING end ... Line 1 Line 2 Line 3
setw() and setfill() manipulators
setw manipulator sets the width of the filed assigned for the output.
The field width determines the minimum number of characters to be written in some output representations. If the standard width of the representation is shorter than the field width, the representation is padded with fill characters (using setfill).
setfill character is used in output insertion operations to fill spaces when results have to be padded to the field width.
Syntax
setw([number_of_characters]); setfill([character]);
Consider the example
#include <iostream.h> #include <iomanip.h> int main() { cout<<"USING setw() ..............\n"; cout<< setw(10) <<11<<"\n"; cout<< setw(10) <<2222<<"\n"; cout<< setw(10) <<33333<<"\n"; cout<< setw(10) <<4<<"\n"; cout<<"USING setw() & setfill() [type- I]...\n"; cout<< setfill('0'); cout<< setw(10) <<11<<"\n"; cout<< setw(10) <<2222<<"\n"; cout<< setw(10) <<33333<<"\n"; cout<< setw(10) <<4<<"\n"; cout<<"USING setw() & setfill() [type-II]...\n"; cout<< setfill('-')<< setw(10) <<11<<"\n"; cout<< setfill('*')<< setw(10) <<2222<<"\n"; cout<< setfill('@')<< setw(10) <<33333<<"\n"; cout<< setfill('#')<< setw(10) <<4<<"\n"; return 0; }
Output
USING setw() .............. 11 2222 33333 4 USING setw() & setfill() [type- I]... 0000000011 0000002222 0000033333 0000000004 USING setw() & setfill() [type-II]... --------11 ******2222 @@@@@33333 #########4
setf() and setprecision() manipulator
setprecision manipulator sets the total number of digits to be displayed, when floating point numbers are printed.
Syntax
setprecision([number_of_digits]);
cout<<setprecision(5)<<1234.537; // output will be : 1234.5
On the default floating-point notation, the precision field specifies the maximum number of meaningful digits to display in total counting both those before and those after the decimal point. Notice that it is not a minimum and therefore it does not pad the displayed number with trailing zeros if the number can be displayed with less digits than the precision.
In both the fixed and scientific notations, the precision field specifies exactly how many digits to display after the decimal point, even if this includes trailing decimal zeros. The number of digits before the decimal point does not matter in this case.
Syntax
setf([flag_value],[field bitmask]);
field bitmask | flag values |
adjustfield | left, right or internal |
basefield | dec, oct or hex |
floatfield | scientific or fixed |
Consider the example
#include <iostream.h> #include <iomanip.h> int main() { cout<<"USING fixed .......................\n"; cout.setf(ios::floatfield,ios::fixed); cout<< setprecision(5)<<1234.537<< endl; cout<<"USING scientific ..................\n"; cout.setf(ios::floatfield,ios::scientific); cout<< setprecision(5)<<1234.537<< endl; return 0; }
Output
USING fixed ....................... 1234.53700 USING scientific .................. 1234.5
Consider the example to illustrate base fields
#include <iostream.h> #include <iomanip.h> int main() { int num=10; cout<<"Decimal value is :"<< num << endl; cout.setf(ios::basefield,ios::oct); cout<<"Octal value is :"<< num << endl; cout.setf(ios::basefield,ios::hex); cout<<"Hex value is :"<< num << endl; return 0; }
Comments
Post a Comment