YouTip LogoYouTip

Cpp Files Streams

# C++ Files and Streams So far, we have used the **iostream** standard library, which provides the **cin** and **cout** methods for reading from standard input and writing to standard output, respectively. This tutorial introduces how to read from and write to files. This requires another standard library in C++, **fstream**, which defines three new data types: | Data Type | Description | | --- | --- | | ofstream | This data type represents the output file stream and is used to create files and write information to files. | | ifstream | This data type represents the input file stream and is used to read information from files. | | fstream | This data type typically represents the file stream and has both ofstream and ifstream functionalities, meaning it can create files, write to files, and read from files. | To perform file handling in C++, you must include the header files and in your C++ source code file. ## Opening a File Before reading from or writing to a file, the file must be opened. Both **ofstream** and **fstream** objects can be used to open a file for writing. If you only need to open a file for reading, use the **ifstream** object. Here is the standard syntax for the open() function, which is a member of the fstream, ifstream, and ofstream objects. void open(const char *filename, ios::openmode mode); Here, the first parameter of the **open()** member function specifies the name and location of the file to be opened, and the second parameter defines the mode in which the file is opened. | Mode Flag | Description | | --- | --- | | ios::app | Append mode. All output is appended to the end of the file. | | ios::ate | File is opened and positioned at the end of the file. | | ios::in | File is opened for reading. | | ios::out | File is opened for writing. | | ios::trunc | If the file already exists, its contents are truncated before the file is opened, i.e., the file length is set to 0. | You can combine two or more of these modes. For example, if you want to open a file in write mode and truncate it in case it already exists, you can use the following syntax: of
← Android TutorialCpp Standard Library β†’