Opening files for read and write in C++
By: Kamini in C++ Tutorials on 2007-09-17
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; 8: 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 16: 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; 22: 23: cout << "\n***End of file contents.***\n"; 24: 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.
Add Comment
This policy contains information about your privacy. By posting, you are declaring that you understand this policy:
- Your name, rating, website address, town, country, state and comment will be publicly displayed if entered.
- Aside from the data entered into these form fields, other stored data about your comment will include:
- Your IP address (not displayed)
- The time/date of your submission (displayed)
- Your email address will not be shared. It is collected for only two reasons:
- Administrative purposes, should a need to contact you arise.
- To inform you of new comments, should you subscribe to receive notifications.
- A cookie may be set on your computer. This is used to remember your inputs. It will expire by itself.
This policy is subject to change at any time and without notice.
These terms and conditions contain rules about posting comments. By submitting a comment, you are declaring that you agree with these rules:
- Although the administrator will attempt to moderate comments, it is impossible for every comment to have been moderated at any given time.
- You acknowledge that all comments express the views and opinions of the original author and not those of the administrator.
- You agree not to post any material which is knowingly false, obscene, hateful, threatening, harassing or invasive of a person's privacy.
- The administrator has the right to edit, move or remove any comment for any reason and without notice.
Failure to comply with these rules may result in being banned from submitting further comments.
These terms and conditions are subject to change at any time and without notice.
- Data Science
- Android
- React Native
- AJAX
- ASP.net
- C
- C++
- C#
- Cocoa
- Cloud Computing
- HTML5
- Java
- Javascript
- JSF
- JSP
- J2ME
- Java Beans
- EJB
- JDBC
- Linux
- Mac OS X
- iPhone
- MySQL
- Office 365
- Perl
- PHP
- Python
- Ruby
- VB.net
- Hibernate
- Struts
- SAP
- Trends
- Tech Reviews
- WebServices
- XML
- Certification
- Interview
categories
Related Tutorials
Calculating total based on the given quantity and price in C++
Sorting an array of Strings in C++
Matrix using nested for loops in C++
Compute the square root of the sum of the squares of an array in C++
Calculate average using Two-Dimensional Array in C++
Two-Dimensional Array Manipulation in C++
Compiling and Linking Multiple Source Files in C++
Escape Sequences for Nonprintable Characters in C++
Using the Built-in Arithmetic Types in C++
Comments