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. 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 tin can correspond a stream as either a destination or a source of characters of indefinite length. This will exist determined past their usage. C++ provides you with a library that comes with methods for file handling. Allow the states discuss information technology.

In this c++ tutorial, you will larn:

  • 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 iii classes for working with files. These classes include:

  • ofstream– This class represents an output stream. Information technology's used for creating files and writing data to files.
  • ifstream– This class represents an input stream. It'south used for reading data from data files.
  • fstream– This class by and large 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 epitome makes it simple to empathise:

fstream library

To use the above classes of the fstream library, you must include it in your program as a header file. Of grade, you volition use the #include preprocessor directive. You must also include the iostream header file.

How to Open Files

Earlier performing whatever performance on a file, yous must outset open it. If y'all need to write to the file, open it using fstream or ofstream objects. If you lot but need to read from the file, open it using the ifstream object.

The iii 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 manner parameter is optional. It can take any of the following values:
Value Description
ios:: app The Suspend fashion. The output sent to the file is appended to it.
ios::ate Information technology opens the file for the output then moves the read and write control to file'south stop.
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 apply two modes at the same time. You combine them using the | (OR) operator.

Example i:

#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:

Hither is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in the programme to use its functions.
  2. Include the fstream header file in the programme to use its classes.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the primary() function. The program logic should become within its body.
  5. Create an object of the fstream course and give it the name my_file.
  6. Employ the open() function on the above object to create a new file. The out mode allows us to write into the file.
  7. Use if argument to check whether file creation failed.
  8. Message to print on the console if the file was non created.
  9. Finish of the body of if statement.
  10. Utilise an else statement to land what to do if the file was created.
  11. Message to impress on the console if the file was created.
  12. Utilize the shut() function on the object to shut the file.
  13. End of the body of the else statement.
  14. The program must return value if information technology completes successfully.
  15. End of the main() function body.

How to Close Files

In one case a C++ program terminates, it automatically

  • flushes the streams
  • releases the allocated retentivity
  • closes opened files.

All the same, equally a programmer, yous should learn to shut open files before the program terminates.

The fstream, ofstream, and ifstream objects have the close() function for endmost files. The function takes this syntax:

void close();                

How to Write to Files

You tin can write to file correct from your C++ programme. Y'all utilize stream insertion operator (<<) for this. The text to exist written to the file should be enclosed within double-quotes.

Let usa demonstrate this.

Example 2:

#include <iostream> #include <fstream> using namespace std; int chief() { 	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(); 	} 	render 0; }                

Output:

Here is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in the program to use its functions.
  2. Include the fstream header file in the program to use its classes.
  3. Include the std namespace in the program to use its classes without calling it.
  4. Phone call the main() office. The program logic should be added within the body of this function.
  5. Create an instance of the fstream class and give it the proper name my_file.
  6. Employ the open up() office to create a new file named my_file.txt. The file will be opened in the out way for writing into it.
  7. Use an if statement to check whether the file has not been opened.
  8. Text to print on the console if the file is not opened.
  9. End of the body of the if statement.
  10. Use an else statement to state what to exercise if the file was created.
  11. Text to print on the console if the file was created.
  12. Write some text to the created file.
  13. Utilise the shut() function to close the file.
  14. Terminate of the body of the else statement.
  15. The program must return value upon successful completion.
  16. 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 apply the operator in the aforementioned manner you apply it to read user input from the keyboard. However, instead of using the cin object, you apply the ifstream/ fstream object.

Instance 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(); 	render 0; }                

Output:

No such file

Hither is a screenshot of the lawmaking:

Code Explanation:

  1. Include the iostream header file in the plan to use its functions.
  2. Include the fstream header file in the program to utilize its classes.
  3. Include the std namespace in the programme to use its classes without calling it.
  4. Call the main() role. The program logic should be added within the body of this office.
  5. Create an case of the fstream form and give it the proper name my_file.
  6. Use the open up() function to create a new file named my_file.txt. The file will exist opened in the in mode for reading from information technology.
  7. Use an if statement to check whether the file does not exist.
  8. Text to print on the console if the file is not found.
  9. End of the body of the if statement.
  10. Utilise an else statement to state what to do if the file is found.
  11. Create a char variable named ch.
  12. Create a while loop for iterating over the file contents.
  13. Write/store contents of the file in the variable ch.
  14. 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 finish is not reached.
  15. Use a interruption statement to stop reading from the file in one case the end is reached.
  16. Print the contents of variable ch on the console.
  17. End of the while body.
  18. End of the body of the else statement.
  19. Call the close() office to close the file.
  20. The plan must render value upon successful completion.
  21. 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 so 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 exist 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 lot must include it in your programme using the #include preprocessor directive.