C++ Writing To File
What is file handling in C++?
Files store data permanently in a storage device. With file handling, the output from a program can be stored in a file. Various operations can be performed on the data while in the file.
A stream is an abstraction of a device where input/output operations are performed. You can represent a stream as either a destination or a source of characters of indefinite length. This will be determined by their usage. C++ provides you with a library that comes with methods for file handling. Let us discuss it.
In this c++ tutorial, you will learn:
- What is file handling in C++?
- The fstream Library
- How to Open Files
- How to Close Files
- How to Write to Files
- How to Read from Files
The fstream Library
The fstream library provides C++ programmers with three classes for working with files. These classes include:
- ofstream– This class represents an output stream. It's used for creating files and writing information to files.
- ifstream– This class represents an input stream. It's used for reading information from data files.
- fstream– This class generally represents a file stream. It comes with ofstream/ifstream capabilities. This means it's capable of creating files, writing to files, reading from data files.
The following image makes it simple to understand:
To use the above classes of the fstream library, you must include it in your program as a header file. Of course, you will use the #include preprocessor directive. You must also include the iostream header file.
How to Open Files
Before performing any operation on a file, you must first open it. If you need to write to the file, open it using fstream or ofstream objects. If you only need to read from the file, open it using the ifstream object.
The three objects, that is, fstream, ofstream, and ifstream, have the open() function defined in them. The function takes this syntax:
open (file_name, mode);
- The file_name parameter denotes the name of the file to open.
- The mode parameter is optional. It can take any of the following values:
Value | Description |
---|---|
ios:: app | The Append mode. The output sent to the file is appended to it. |
ios::ate | It opens the file for the output then moves the read and write control to file's end. |
ios::in | It opens the file for a read. |
ios::out | It opens the file for a write. |
ios::trunc | If a file exists, the file elements should be truncated prior to its opening. |
It is possible to use two modes at the same time. You combine them using the | (OR) operator.
Example 1:
#include <iostream> #include <fstream> using namespace std; int main() { fstream my_file; my_file.open("my_file", ios::out); if (!my_file) { cout << "File not created!"; } else { cout << "File created successfully!"; my_file.close(); } return 0; }
Output:
Here is a screenshot of the code:
Code Explanation:
- Include the iostream header file in the program to use its functions.
- Include the fstream header file in the program to use its classes.
- Include the std namespace in our code to use its classes without calling it.
- Call the main() function. The program logic should go within its body.
- Create an object of the fstream class and give it the name my_file.
- Apply the open() function on the above object to create a new file. The out mode allows us to write into the file.
- Use if statement to check whether file creation failed.
- Message to print on the console if the file was not created.
- End of the body of if statement.
- Use an else statement to state what to do if the file was created.
- Message to print on the console if the file was created.
- Apply the close() function on the object to close the file.
- End of the body of the else statement.
- The program must return value if it completes successfully.
- End of the main() function body.
How to Close Files
Once a C++ program terminates, it automatically
- flushes the streams
- releases the allocated memory
- closes opened files.
However, as a programmer, you should learn to close open files before the program terminates.
The fstream, ofstream, and ifstream objects have the close() function for closing files. The function takes this syntax:
void close();
How to Write to Files
You can write to file right from your C++ program. You use stream insertion operator (<<) for this. The text to be written to the file should be enclosed within double-quotes.
Let us demonstrate this.
Example 2:
#include <iostream> #include <fstream> using namespace std; int main() { fstream my_file; my_file.open("my_file.txt", ios::out); if (!my_file) { cout << "File not created!"; } else { cout << "File created successfully!"; my_file << "Guru99"; my_file.close(); } return 0; }
Output:
Here is a screenshot of the code:
Code Explanation:
- Include the iostream header file in the program to use its functions.
- Include the fstream header file in the program to use its classes.
- Include the std namespace in the program to use its classes without calling it.
- Call the main() function. The program logic should be added within the body of this function.
- Create an instance of the fstream class and give it the name my_file.
- Use the open() function to create a new file named my_file.txt. The file will be opened in the out mode for writing into it.
- Use an if statement to check whether the file has not been opened.
- Text to print on the console if the file is not opened.
- End of the body of the if statement.
- Use an else statement to state what to do if the file was created.
- Text to print on the console if the file was created.
- Write some text to the created file.
- Use the close() function to close the file.
- End of the body of the else statement.
- The program must return value upon successful completion.
- End of the body of the main() function.
How to Read from Files
You can read information from files into your C++ program. This is possible using stream extraction operator (>>). You use the operator in the same way you use it to read user input from the keyboard. However, instead of using the cin object, you use the ifstream/ fstream object.
Example 3:
#include <iostream> #include <fstream> using namespace std; int main() { fstream my_file; my_file.open("my_file.txt", ios::in); if (!my_file) { cout << "No such file"; } else { char ch; while (1) { my_file >> ch; if (my_file.eof()) break; cout << ch; } } my_file.close(); return 0; }
Output:
No such file
Here is a screenshot of the code:
Code Explanation:
- Include the iostream header file in the program to use its functions.
- Include the fstream header file in the program to use its classes.
- Include the std namespace in the program to use its classes without calling it.
- Call the main() function. The program logic should be added within the body of this function.
- Create an instance of the fstream class and give it the name my_file.
- Use the open() function to create a new file named my_file.txt. The file will be opened in the in mode for reading from it.
- Use an if statement to check whether the file does not exist.
- Text to print on the console if the file is not found.
- End of the body of the if statement.
- Use an else statement to state what to do if the file is found.
- Create a char variable named ch.
- Create a while loop for iterating over the file contents.
- Write/store contents of the file in the variable ch.
- Use an if condition and eof() function that is, end of the file, to ensure the compiler keeps on reading from the file if the end is not reached.
- Use a break statement to stop reading from the file once the end is reached.
- Print the contents of variable ch on the console.
- End of the while body.
- End of the body of the else statement.
- Call the close() function to close the file.
- The program must return value upon successful completion.
- End of the body of the main() function.
Summary:
- With file handling, the output of a program can be sent and stored in a file.
- A number of operations can then be applied to the data while in the file.
- A stream is an abstraction that represents a device where input/output operations are performed.
- A stream can be represented as either destination or source of characters of indefinite length.
- The fstream library provides C++ programmers with methods for file handling.
- To use the library, you must include it in your program using the #include preprocessor directive.
C++ Writing To File
Source: https://www.guru99.com/cpp-file-read-write-open.html
Posted by: lynntheigh.blogspot.com
0 Response to "C++ Writing To File"
Post a Comment