What is file handling in C++?

Files store data permanently in a storage device. With file handling, the output from a program tin can be stored in a file. Diverse operations tin can be performed on the data while in the file.

A stream is an abstraction of a device where input/output operations are performed. Y'all can represent a stream as either a destination or a source of characters of indefinite length. This will be adamant by their usage. C++ provides you lot with a library that comes with methods for file handling. Let united states hash out 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 3 classes for working with files. These classes include:

  • ofstream– This class represents an output stream. It'due south used for creating files and writing information to files.
  • ifstream– This grade represents an input stream. Information technology's used for reading information from data files.
  • fstream– This course generally represents a file stream. It comes with ofstream/ifstream capabilities. This ways information technology's capable of creating files, writing to files, reading from data files.

The following image makes information technology simple to understand:

fstream library

To use the above classes of the fstream library, you must include it in your programme equally a header file. Of course, you will use the #include preprocessor directive. Y'all must too include the iostream header file.

How to Open Files

Earlier performing any operation on a file, y'all must kickoff open it. If you need to write to the file, open information technology using fstream or ofstream objects. If you simply demand 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 office 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 mode. The output sent to the file is appended to it.
ios::ate It opens the file for the output so moves the read and write control to file's finish.
ios::in Information technology opens the file for a read.
ios::out Information technology 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 2 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 up("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 lawmaking:

Code Explanation:

  1. Include the iostream header file in the plan to utilise its functions.
  2. Include the fstream header file in the program to apply its classes.
  3. Include the std namespace in our lawmaking to use its classes without calling it.
  4. Telephone call the main() office. The plan logic should go inside its trunk.
  5. Create an object of the fstream class 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 united states to write into the file.
  7. Use if argument to check whether file creation failed.
  8. Bulletin to impress on the console if the file was not created.
  9. End of the body of if statement.
  10. Apply an else statement to country what to practise if the file was created.
  11. Message to print on the panel if the file was created.
  12. Use the close() function on the object to close the file.
  13. Stop of the body of the else statement.
  14. The program must return value if it completes successfully.
  15. Terminate of the main() function torso.

How to Shut Files

Once a C++ program terminates, it automatically

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

Even so, as a programmer, you should larn to close open files before the program terminates.

The fstream, ofstream, and ifstream objects have the shut() role for closing files. The function takes this syntax:

void close();                

How to Write to Files

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

Let u.s.a. demonstrate this.

Example two:

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

  1. Include the iostream header file in the plan 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 employ its classes without calling it.
  4. Telephone call the principal() function. The program logic should exist added within the torso of this part.
  5. Create an instance of the fstream class and give information technology the name my_file.
  6. Use the open() role to create a new file named my_file.txt. The file will exist opened in the out mode for writing into it.
  7. Use an if argument to check whether the file has not been opened.
  8. Text to impress 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 impress on the console if the file was created.
  12. Write some text to the created file.
  13. Use the close() role to close the file.
  14. End of the body of the else argument.
  15. The plan must return value upon successful completion.
  16. End of the trunk of the main() office.

How to Read from Files

You lot can read data from files into your C++ plan. This is possible using stream extraction operator (>>). You use the operator in the aforementioned fashion yous use it to read user input from the keyboard. However, instead of using the cin object, y'all use the ifstream/ fstream object.

Example iii:

#include <iostream> #include <fstream> using namespace std; int main() { 	fstream my_file; 	my_file.open up("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.shut(); 	return 0; }                

Output:

No such file

Hither is a screenshot of the code:

Lawmaking Explanation:

  1. Include the iostream header file in the program to use its functions.
  2. Include the fstream header file in the plan to utilise its classes.
  3. Include the std namespace in the program to employ its classes without calling it.
  4. Call the master() part. The program logic should be added within the body of this function.
  5. Create an instance of the fstream class and give information technology the proper noun my_file.
  6. Use the open up() part to create a new file named my_file.txt. The file will be opened in the in mode for reading from it.
  7. Utilize an if statement to cheque whether the file does non exist.
  8. Text to print on the console if the file is not plant.
  9. Cease of the body of the if statement.
  10. Utilise an else argument to land what to practice 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 status 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.
  15. Utilize a break statement to end reading from the file in one case the end is reached.
  16. Impress the contents of variable ch on the console.
  17. End of the while body.
  18. End of the body of the else statement.
  19. Telephone call the close() function to shut the file.
  20. The program must return 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 tin then exist applied to the data while in the file.
  • A stream is an brainchild 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 treatment.
  • To use the library, yous must include it in your program using the #include preprocessor directive.