What is file handling in C++?

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

A stream is an brainchild of a device where input/output operations are performed. You can correspond a stream equally either a destination or a source of characters of indefinite length. This volition exist adamant past their usage. C++ provides you with a library that comes with methods for file handling. Permit us discuss information technology.

In this c++ tutorial, you lot volition larn:

  • What is file handling in C++?
  • The fstream Library
  • How to Open Files
  • How to Shut 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 grade 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 post-obit image makes information technology elementary to understand:

fstream library

To use the above classes of the fstream library, you must include it in your program every bit a header file. Of course, you will use the #include preprocessor directive. You must also include the iostream header file.

How to Open Files

Earlier performing any functioning on a file, you must first open information technology. If you need to write to the file, open it using fstream or ofstream objects. If you lot just need to read from the file, open it using the ifstream object.

The three objects, that is, fstream, ofstream, and ifstream, accept 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 tin have any of the following values:
Value Description
ios:: app The Append manner. The output sent to the file is appended to information technology.
ios::ate Information technology opens the file for the output then moves the read and write control to file'south cease.
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 fourth dimension. You combine them using the | (OR) operator.

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

Output:

Hither is a screenshot of the code:

Lawmaking Explanation:

  1. Include the iostream header file in the program to employ its functions.
  2. Include the fstream header file in the program to use its classes.
  3. Include the std namespace in our code to use its classes without calling it.
  4. Call the main() function. The program logic should go within its body.
  5. Create an object of the fstream class and give it the proper name my_file.
  6. Utilise the open() function on the to a higher place object to create a new file. The out mode allows us to write into the file.
  7. Utilise if statement to check whether file creation failed.
  8. Message to print on the console if the file was not created.
  9. End of the body of if statement.
  10. Use an else statement to state what to practice if the file was created.
  11. Bulletin to print on the console if the file was created.
  12. Apply the close() function on the object to close the file.
  13. End of the body of the else statement.
  14. The program must return value if it completes successfully.
  15. End of the main() role torso.

How to Close Files

Once a C++ programme terminates, it automatically

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

Withal, every bit a programmer, y'all should learn to close open files before the programme terminates.

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

void close();                

How to Write to Files

You can write to file correct from your C++ program. You use stream insertion operator (<<) for this. The text to be written to the file should be enclosed inside double-quotes.

Let usa demonstrate this.

Example ii:

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

Output:

Hither is a screenshot of the code:

Code Explanation:

  1. Include the iostream header file in the program to utilise its functions.
  2. Include the fstream header file in the program to utilise its classes.
  3. Include the std namespace in the program to apply its classes without calling information technology.
  4. Phone call the chief() function. The program logic should be added within the torso of this part.
  5. Create an case of the fstream grade and requite it the name my_file.
  6. Use the open up() office to create a new file named my_file.txt. The file volition be opened in the out mode for writing into it.
  7. Utilise 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. Apply 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. Use the close() role to shut the file.
  14. Finish of the body of the else statement.
  15. The plan must render value upon successful completion.
  16. Finish of the body of the chief() office.

How to Read from Files

Y'all can read information from files into your C++ program. This is possible using stream extraction operator (>>). You lot use the operator in the aforementioned way you utilise it to read user input from the keyboard. However, instead of using the cin object, you apply 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 (i) { 			my_file >> ch; 			if (my_file.eof()) 				break;  			cout << ch; 		}  	} 	my_file.close(); 	render 0; }                

Output:

No such file

Here is a screenshot of the lawmaking:

Code Explanation:

  1. Include the iostream header file in the programme to utilise its functions.
  2. Include the fstream header file in the program to use its classes.
  3. Include the std namespace in the plan to use its classes without calling it.
  4. Call the main() function. The program logic should be added inside the body of this function.
  5. Create an example of the fstream form and give it the proper name my_file.
  6. Utilize the open() function to create a new file named my_file.txt. The file volition exist opened in the in mode for reading from information technology.
  7. Use an if argument to check whether the file does not be.
  8. Text to impress on the console if the file is non constitute.
  9. Stop of the torso of the if argument.
  10. Utilize 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. Utilise an if condition and eof() function that is, cease of the file, to ensure the compiler keeps on reading from the file if the stop is not reached.
  15. Use a suspension argument to stop reading from the file once the end is reached.
  16. Impress the contents of variable ch on the console.
  17. End of the while body.
  18. Stop of the body of the else statement.
  19. Phone call the shut() function to close the file.
  20. The program must return value upon successful completion.
  21. Terminate of the trunk of the chief() function.

Summary:

  • With file handling, the output of a program can exist sent and stored in a file.
  • A number of operations can and so be applied to the information while in the file.
  • A stream is an abstraction that represents a device where input/output operations are performed.
  • A stream tin 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, you lot must include it in your program using the #include preprocessor directive.