File handling in C++ allows programs to create, read, write, and manipulate files on disk. It utilizes the library, which includes three primary classes:
ifstream: For reading files.
ofstream: For writing to files.
fstream: For both reading and writing.
To handle files, you typically follow these s...
File handling in C++ allows programs to create, read, write, and manipulate files on disk. It utilizes the library, which includes three primary classes:
ifstream: For reading files.
ofstream: For writing to files.
fstream: For both reading and writing.
To handle files, you typically follow these steps:
Open a file using open() or by passing the filename to the constructor.
Perform operations (read/write) using appropriate methods.
Close the file with close() to free resources.
File modes include ios::in, ios::out, ios::app, and ios::ate for various file operations1
Error Handling
C++ also provides mechanisms to check for errors during file operations. Functions like is_open(), eof(), and fail() help determine if a file was successfully opened, if the end of the file has been reached, or if an error occurred during an operation.
Overall, file handling in C++ is essential for applications that require persistent data storage and retrieval, enabling developers to create robust programs that interact with external data sources effectively.
Created by:- Suryavansh Rana
Contact: [email protected]
Size: 7.66 MB
Language: en
Added: Nov 22, 2024
Slides: 82 pages
Slide Content
FILE HANDLING THROUGH C++
What are “FILES”? Why do we need them?
A file is a collection of information, usually stored on a computer’s disk. Information can be saved to files and then later reused. Computers store files to secondary storage so that the content of files remain intact when a computer shuts down. All files are assigned a name that is used for identification Purposes by the Operating System. When a compute reads a file, it copies the file from the storage device to memory ; when it writes to a file, it transfers data from the memory to the storage device
Why do we need files?
All the programs we have looked so far use input only from the keyboard, and output only to the screen - Data held in variables is temporary and is lost when the program execution is finished In order to store data permanently, we need to store it in the files on the hard disk.
*File stream -Input Stream -Output Stream
A file stream act as an interface between the program and files A stream that flows from an input device to the main memory (from: keyboard, disk drive, scanner or network connection) Basically, the stream that supplies data to the program is known as input stream . A stream that flows from the main memory to an output device (to: screen, printer, disk drive or network connection) The stream that receives data from the program is known as output stream.
The input operation involves the creation of an input stream and linking it with the program and the input file. Similarly, the output involves establishing an output stream with the necessary links with the program and output file.
Using “ ftream ” A Stream is a sequence of bytes. It is a general name given to flow of data . Different streams are used to different kind of data flow. Ifstream class represents input disk files. Ofstream class represents output disk files Fstream – for both input and output
As stated earlier, for opening a file, we must create a file stream and then link it to the filename. A file stream can be defined using the classes ifstream , ofstream and fstream that are contained in header file fstream . The class to be used depends upon the purpose, that is, whether we want to read data from file or write data to it. A file can be opened in two ways: 1. Using the constructor function of the class. 2. Using the member function open() of the class.
Before we can use “input” and “output” stream in a program, we must “ create ” it
Opening Files Using Constructor Opening Files Using open()
Opening Files using constructor The ‘ ofstream ’ class in cpp is used for writing data to files. It is the part of the ‘< fstream >’ header and stands for ‘output file stream’ . File access requires the inclusion of header file ‘ fstream ’. Before data can be written to or read from a file, the file must be opened. Use ofstream for output stream ofstream objectname (“filename”);
Let’s Do it Practically
1. Include the Header: # include < fstream > 2. Create an object to open File for writing Ofstream outfile ( “example.txt” ) 3. Write data: Use the ‘<<‘ operator Bjarne Stroustrup Outfille << “Hello World?” ; 4. Close the File: Always close the file when done:
Outfile.close (); Results? Do it yourself…… Or AI gonna work ………………………… 🤬🤬🤬y@#$#!!!! 🤬 🤬🤬v🤬🤬🤬🤬🤬🤬🤬🤬f#$$#$%^&*%$!!!!!! 🤬 🤬🤬🤬🤬f#$$#$%^&*%$!!!!!! 😂😂😂😂
In C++, ifstream stands for input file stream. It is a class used to read data from files. ifstream
What is ifstream ? Purpose: ifstream allows your program to read data from files, similar to how you use cin to read input from the keyboard. Library Requirement: To use ifstream , you need to include the < fstream > header in your program. Basic Usage Creating an ifstream Object: You create an ifstream object that is associated with a specific file you want to read. Opening a File: You can open a file using the open() method or directly in the constructor. Reading Data: You can read data from the file using various methods, such as the extraction operator ( >> ) or the getline () function for reading lines. Closing the File: After you're done reading, it's good practice to close the file using the close() method.
Bjarne stroustrup
Let’s Create one And open the file we’ve created using “ ofstream ” earlier
Opening Files Using Constructor Opening Files Using open()
Using the open() Method: This method allows you to create the file stream object first and then open the file later. This is particularly useful if you want to control when and how you open the file, or if you need to change the file being opened during program execution. ifstream inputFile ; // Declare an ifstream object inputFile.open ( "example.txt" ); // Open the file using open() inputFile.close () inputFile.open ( "example2.txt" ); // Open the znother file using open() inputFile.close ()
We can use fstream for both input and output and also we can use file modes to read, write, handle etc
To open files in cpp . We used the ‘ fstream ’ ‘ ifstream ’ ‘ ofstream ’ classes. The ‘open()’ function is specified to utilize file name and mode .The syntax is : Fstream_object.open ( “filename” , mode); Common modes include: ios ::in : Open for Reading ios ::out : Open for Writing(overwrites existing content) ios ::app : Open for appending data Always check if the file opened successfully using ‘ is_open ()’, and close it with ‘close()’ after operations are complete.
Let’s do some practical work for better understanding …..
Sorry! Might be system bug
Now let’s see the function of append……… Again run run the program…..
Have you noticed something Program has printed only Snow Because cin >>name stops reading at the first whitespace. To allow for multi-world names (like Snow White), we need to use ‘ getline ()’ instead of ‘ cin ’.
END OF PRESNETATION THANK YOU SO MUCH
WEIGHT !!!
Reading and writing characters from/to disk
The function put() and get() are used for manipulating a file character by character. These functions are members of ostream and istream respectively
Put() is used for output to the file Let’s create one for better understanding…….
get() is used to get input from file
Now let’s do for this also
w rite() and read() also exists They are designed to read block of binary data
Read() The read() function is used to read object( sequenceof bytes) to the file. Syntax of read()function f stream fin ; f in .read (( char *)& obj , sizeof ( obj ));
w rite() The write() function is used to write object or record (sequence of bytes) to the file. A record may be an array, structure or class Sinetax yaani Syntax of write() function f stream fout ; f out. write (( char* )& obj,sizeof ( obj ));
Let’s go further only 7 topics are left
Do you know if you write a program for writing to a file at the end if you write “file read successfully”, if your program failed to run even then it’ll show file read successfully But don’t worry here comes error handling
You noticed? We did error handling everywhere …………………
When working with file I/O operations in C++, it’s essential to understand the state of the stream. The stream can be in various states such as good, fail, bad, or at the end of the file (EOF). C++ provides several functions to check and manage these states. Here we will discuss four critical functions: bad(), fail(), good(), and eof ().
1. bad() - Checking for a Bad Stream State Definition : The bad() function checks if the stream is in a "bad" state. A stream enters a bad state when a serious error occurs, such as a hardware failure or a system-level issue. Return Type : bool Returns true if the stream is in a bad state, and false otherwise. Usage Example : A stream is considered "bad" if an I/O operation cannot be completed due to a system failure or corruption.
2 fail() - Checking for a Fail Stream State Definition : The fail() function checks if the stream has failed during an operation, but not due to a catastrophic system failure. Failures can include invalid data types or reading past the end of the file. Return Type : bool Returns true if the stream has encountered an error during an I/O operation (e.g., invalid input or reading a file past its end), and false otherwise. Usage Example : A stream is in a failed state when it cannot perform the requested operation due to format issues, type mismatches, or attempts to read beyond the end of the file.
3. good() - Checking if the Stream is in a Good State Definition : The good() function checks if the stream is in a valid state, meaning no errors or end-of-file conditions have occurred, and the stream is ready for the next operation. Return Type : bool Returns true if the stream is in a good state, and false otherwise. Usage Example : If no error has occurred, and the stream is functioning correctly, it is considered "good."
4 . eof () - Checking for End of File (EOF) Definition : The eof () function checks if the stream has reached the end of the file. This is particularly important when reading data from a file, as it signals that no more data can be read. Return Type : bool Returns true if the end of the file has been reached, and false otherwise. Usage Example : The EOF function is often used in loops to read through a file until no more data is available.
So This is what file handling in cpp looks likes. There’s still way more to go but being content with what one have is true happiness. And yes thanks to respected Dr. Manoj Sir who gave us this project, he’s kind hearted gentleman who’s too much open-hearted, that he will definitely not hesitate to give full marks. Thank you Sir once again for giving full marks. Thanks to everybody, especially audience coz without you there was no fun. So all the best for your exams … May everyone top without studying…
Special Thanks to My Parents Teammates Professors Staff Manager & Director Miss Reena Rani & Kirti Sharma Designer & Editor Suryavansh Rana THANKS TO Chrome Slideshare LAVA Lenovo Microsoft Perplexity Youtube Google Pintrest of course powerpoint