Opening files for read and write in C++

By: Kamini Emailed: 1768 times Printed: 2515 times    

Latest comments
By: rohit kumar - how this program is work
By: Kirti - Hi..thx for the hadoop in
By: Spijker - I have altered the code a
By: ali mohammed - why we use the java in ne
By: ali mohammed - why we use the java in ne
By: mizhelle - when I exported the data
By: raul - no output as well, i'm ge
By: Rajesh - thanx very much...
By: Suindu De - Suppose we are executing

To open the file myfile.cpp with an ofstream object, declare an instance of an ofstream object and pass in the filename as a parameter:

ofstream fout("myfile.cpp");

Opening this file for input works exactly the same way, except it uses an ifstream object:

ifstream fin("myfile.cpp");

Note that fout and fin are names you assign; here fout has been used to reflect its similarity to cout, and fin has been used to reflect its similarity to cin.

One important file stream function that you will need right away is close(). Every file stream object you create opens a file for either reading or writing (or both). It is important to close() the file after you finish reading or writing; this ensures that the file won't be corrupted and that the data you've written is flushed to the disk.

Once the stream objects are associated with files, they can be used like any other stream objects. Listing below illustrates this.

Opening files for read and write.

1:     #include <fstream.h>
2:     int main()
3:     {
4:        char fileName[80];
5:        char buffer[255];    // for user input
6:        cout << "File name: ";
7:        cin >> fileName;
9:        ofstream fout(fileName);  // open for writing
10:       fout << "This line written directly to the file...\n";
11:       cout << "Enter text for the file: ";
12:       cin.ignore(1,'\n');  // eat the newline after the file name
13:       cin.getline(buffer,255);  // get the user's input
14:       fout << buffer << "\n";   // and write it to the file
15:       fout.close();             // close the file, ready for reopen
17:       ifstream fin(fileName);    // reopen for reading
18:       cout << "Here's the contents of the file:\n";
19:       char ch;
20:       while (fin.get(ch))
21:          cout << ch;
23:       cout << "\n***End of file contents.***\n";
25:       fin.close();            // always pays to be tidy
26:     return 0;
27: }

Output: File name: test1
Enter text for the file: This text is written to the file!
Here's the contents of the file:
This line written directly to the file...
This text is written to the file!

***End of file contents.***

Analysis: On line 4, a buffer is set aside for the filename, and on line 5 another buffer is set aside for user input. The user is prompted to enter a filename on line 6, and this response is written to the fileName buffer. On line 9, an ofstream object is created, fout, which is associated with the new filename. This opens the file; if the file already exists, its contents are thrown away.

On line 10, a string of text is written directly to the file. On line 11, the user is prompted for input. The newline character left over from the user's input of the filename is eaten on line 12, and the user's input is stored into buffer on line 13. That input is written to the file along with a newline character on line 14, and then the file is closed on line 15.

On line 17, the file is reopened, this time in input mode, and the contents are read, one character at a time, on lines 20 and 21.

C++ Home | All C++ Tutorials | Latest C++ Tutorials

Sponsored Links

If this tutorial doesn't answer your question, or you have a specific question, just ask an expert here. Post your question to get a direct answer.

Bookmark and Share


Be the first one to add a comment

Your name (required):

Your email(required, will not be shown to the public):

Your sites URL (optional):

Your comments:

More Tutorials by Kamini
Importing the Certificate Reply from the CA example using keytool in Java
The switch Statement example in Java
Joins example in SQL
ERRNO.H Header File in C
XDoclet struts-config.xml in Struts
Macro Substitution using #define in C
Using Checkbox & Radio Tags, html:select, html:options in Struts Forms
Do while Loops in C
Functions in C
Opening files for read and write in C++
Operator Precedence in C++
StringItem sample program in J2ME
AWT-based applications with a User Interface Window in Java
store() and load() example in Java
Stray or Dangling Pointers in C++

More Tutorials in C++
Two-Dimensional Array Manipulation in C++
Calculate average using Two-Dimensional Array in C++
Compute the square root of the sum of the squares of an array in C++
Matrix using nested for loops in C++
Sorting an array of Strings in C++
Calculating total based on the given quantity and price in C++
Compiling and Linking Multiple Source Files in C++
Enumerations in C++
Program to add two numbers in C++
Comments in C++
while loop in C++
for loop in C++
Programming errors a compiler will detect in C++
if in C++
Using the Built-in Arithmetic Types in C++

More Latest News
Most Viewed Articles (in C++ )
The Stack and the Free Store in C++
Operator Precedence in C++
Getting User Input Using cin in C++
Function overloading in C++
Multi-Line Literals in C++
Calculating total based on the given quantity and price in C++
Using Comments in a C++ Program
do...while Loops in C++
for Loops in C++
Using switch Statements in C++
What Is a Pointer in C++?
The indirection operator (*) - dereference operator.
Dot (.) vs Arrow (->) to access data members in C++
this Pointer in C++
Converting Pointer Parameters in C++ to Java
Most Emailed Articles (in C++)
Demonstrating global and local variables in C++
C++ and Object-Oriented Programming
Using cout in C++
Use of Conditional (Ternary) Operator in C++
const Member Functions in C++
Classes with Other Classes as Member Data in C++
What Is a Pointer in C++?
Manipulating Data by Using Pointers
Stray or Dangling Pointers in C++
C++ Destructors Versus Java Finalization
atoi(), itoa() in C++
strcat() and strncat() sample program in C++
Using #define, The Preprocessor and the Compiler in C++
Getting User Input Using cin in C++
Pass by Reference in C++ functions