Using << to Read a File in C++
What is file handling in C++?
Files store data permanently in a storage device. With file treatment, the output from a plan can be stored in a file. Diverse operations can exist performed on the information while in the file.
A stream is an brainchild of a device where input/output operations are performed. Yous can represent a stream every bit either a destination or a source of characters of indefinite length. This will be determined by their usage. C++ provides you lot with a library that comes with methods for file treatment. Let us discuss it.
In this c++ tutorial, you volition learn:
- What is file treatment 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. Information technology'south used for reading data from data files.
- fstream– This grade more often than not represents a file stream. Information technology comes with ofstream/ifstream capabilities. This ways it'south capable of creating files, writing to files, reading from data files.
The following image makes it uncomplicated to understand:
To use the above classes of the fstream library, you must include it in your programme as a header file. Of course, you will apply the #include preprocessor directive. You must likewise include the iostream header file.
How to Open Files
Before performing any functioning on a file, y'all must first open it. If you lot need to write to the file, open up it using fstream or ofstream objects. If you but demand to read from the file, open information technology using the ifstream object.
The three objects, that is, fstream, ofstream, and ifstream, accept the open up() role defined in them. The part 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 information technology. |
| ios::ate | It opens the file for the output then moves the read and write command 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 one:
#include <iostream> #include <fstream> using namespace std; int primary() { fstream my_file; my_file.open("my_file", ios::out); if (!my_file) { cout << "File non created!"; } else { cout << "File created successfully!"; my_file.shut(); } return 0; } Output:
Hither is a screenshot of the code:
Lawmaking Explanation:
- Include the iostream header file in the programme to use its functions.
- Include the fstream header file in the programme to employ its classes.
- Include the std namespace in our code to apply its classes without calling it.
- Call the principal() function. The program logic should go within its body.
- Create an object of the fstream form and give information technology the name my_file.
- Use the open() function on the above object to create a new file. The out mode allows usa 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.
- Terminate of the body of if statement.
- Use an else statement to land what to practice if the file was created.
- Message to impress on the console if the file was created.
- Apply the close() function on the object to shut the file.
- Cease of the trunk of the else statement.
- The plan must return value if it completes successfully.
- End of the chief() function torso.
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 shut open files earlier the plan terminates.
The fstream, ofstream, and ifstream objects have the close() function for closing files. The part takes this syntax:
void close();
How to Write to Files
You tin 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 exist enclosed within double-quotes.
Let us demonstrate this.
Example 2:
#include <iostream> #include <fstream> using namespace std; int principal() { fstream my_file; my_file.open up("my_file.txt", ios::out); if (!my_file) { cout << "File not created!"; } else { cout << "File created successfully!"; my_file << "Guru99"; my_file.shut(); } return 0; } Output:
Here is a screenshot of the lawmaking:
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 utilize its classes without calling it.
- Call the main() part. The program logic should be added within the body of this role.
- Create an example of the fstream course 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 style for writing into it.
- Employ an if statement to cheque whether the file has non been opened.
- Text to print on the console if the file is not opened.
- Finish of the body of the if statement.
- Use an else argument to country what to do if the file was created.
- Text to impress on the console if the file was created.
- Write some text to the created file.
- Use the shut() function to close the file.
- End of the trunk of the else statement.
- The program must return value upon successful completion.
- End of the body of the main() part.
How to Read from Files
Yous can read information from files into your C++ program. This is possible using stream extraction operator (>>). Yous utilize the operator in the aforementioned way you lot use it to read user input from the keyboard. Notwithstanding, instead of using the cin object, you use the ifstream/ fstream object.
Instance 3:
#include <iostream> #include <fstream> using namespace std; int chief() { 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 lawmaking:
Code Explanation:
- Include the iostream header file in the program to use its functions.
- Include the fstream header file in the programme to utilize its classes.
- Include the std namespace in the program to utilise its classes without calling it.
- Telephone call the main() role. The program logic should be added within the torso of this function.
- Create an case of the fstream course and give it the name my_file.
- Utilize the open() function to create a new file named my_file.txt. The file will be opened in the in style 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 argument to cease reading from the file once the end is reached.
- Impress the contents of variable ch on the console.
- End of the while body.
- Stop of the body of the else statement.
- Call the close() function to close the file.
- The plan must render value upon successful completion.
- Finish of the trunk of the primary() function.
Summary:
- With file handling, the output of a program can be sent and stored in a file.
- A number of operations tin can and then exist 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 exist represented equally 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 lot must include it in your program using the #include preprocessor directive.
Source: https://www.guru99.com/cpp-file-read-write-open.html
0 Response to "Using << to Read a File in C++"
Post a Comment