Read write file cpp

C++ Files

To use the fstream library, include both the standard AND the header file:

Example

There are three classes included in the fstream library, which are used to create, write or read files:

Class Description
ofstream Creates and writes to files
ifstream Reads from files
fstream A combination of ofstream and ifstream: creates, reads, and writes to files

Create and Write To a File

To create a file, use either the ofstream or fstream class, and specify the name of the file.

To write to the file, use the insertion operator (

Example

int main() // Create and open a text file
ofstream MyFile(«filename.txt»);

// Close the file
MyFile.close();
>

Why do we close the file?

It is considered good practice, and it can clean up unnecessary memory space.

Read a File

To read from a file, use either the ifstream or fstream class, and the name of the file.

Note that we also use a while loop together with the getline() function (which belongs to the ifstream class) to read the file line by line, and to print the content of the file:

Example

// Create a text string, which is used to output the text file
string myText;

// Read from the text file
ifstream MyReadFile(«filename.txt»);

// Use a while loop together with the getline() function to read the file line by line
while (getline (MyReadFile, myText)) // Output the text from the file
cout >

// Close the file
MyReadFile.close();

Источник

How to Read and Write to a File in C++

In this article, we are going to show you how to read and write to a file in the C++ programming language by using several examples. To understand C++ file operations like read and write, we must first understand the concept of a stream in C++.

Читайте также:  Php get class null

What is a Stream?

A stream is simply a flow of data or characters. There are two types of streams: input streams and output streams. An input stream is used to read the data from an external input device such as a keyboard, while an output stream is used to write data to the external output device such as a monitor. A file can be considered as both an input and output source.

In C++, we use a stream to send or to receive data to or from an external source.

We can use built-in classes to access an input/output stream, i.e., “ios”.

Here is the stream class hierarchy of the C++ programming language:

The “cin” and “cout” objects are used to read the data from the keyboard and to display the output on the monitor, respectively. In addition, “ifstream,” which stands for “input file stream,” is used to read a stream of data from a file, and “ofstream,” which stands for “output file stream,” is used to write a stream of data to a file.

The “iostram.h” file contains all the required standard input/output stream classes in the C++ programming language.

Examples

Now that you understand the basics of streams, we will discuss the following examples to help you to better understand file operations in C++:

  • Example 1: Open and Close a File
  • Example 2: Write to a File
  • Example 3: Read from a File
  • Example 4: Read and Write to a File
  • Example 5: Read and Write to a Binary File

Example 1: Open and Close a File

In this example program, we will demonstrate how to open/create a file and how to close the file in C++. As you can see in the below program, we have included the library required for file operations.

To open and close a file, we need an object of ofstream. Then, to read or write to a file, we have to open the file. We have included the fstream header file at line number-1 so that we can access ofstream class.

We have declared a myFile_Handler as an object of ofstream inside the main function. We can then use the open() function to create an empty file and the close() function to close the file.

Читайте также:  Implement Sticky Header and Footer with CSS

int main ( )
{
ofstream myFile_Handler ;

// File Open
myFile_Handler. open ( «File_1.txt» ) ;

// File Close
myFile_Handler. close ( ) ;
return 0 ;
}

Now, we will compile the program and examine the output. As you can see in the output window below, the “File_1.txt” file was created after executing the program. The size of the file is zero since we have not written any content in the file.

Example 2: Write to a File

In the previous example program, we showed you how to open a file and how to close the file. Now, we will show you how to write something in a file.

int main ( )
{
ofstream myFile_Handler ;
// File Open
myFile_Handler. open ( «File_1.txt» ) ;

// File Close
myFile_Handler. close ( ) ;
return 0 ;
}

Now, we will compile the above program and execute it. As you can see below, we have successfully written to the file File_1.txt.

Example 3: Read from a File

In the previous examples, we showed you how to write content to a file. Now, let’s read the content from the file that we created in Example-2 and display the content on the standard output device, i.e., the monitor.

We use the getline() function to read the complete line from the file and then “cout” to print the line on the monitor.

int main ( )
{
ifstream myFile_Handler ;
string myLine ;

// File Open in the Read Mode
myFile_Handler. open ( «File_1.txt» ) ;

if ( myFile_Handler. is_open ( ) )
{
// Keep reading the file
while ( getline ( myFile_Handler, myLine ) )
{
// print the line on the standard output
cout }
// File Close
myFile_Handler. close ( ) ;
}
else
{
cout }
return 0 ;
}

Now, we will print the content of File_1.txt using the following command: cat File_1.txt. Once we compile and execute the program, it is clear that the output matches the content of the file. Therefore, we have successfully read the file and printed the content of the file to the monitor.

Example 4: Read and Write to a File

So far, we have showed you how to open, read, write, and close a file. In C++, we can also read and write to a file at the same time. To both read and write to a file, we have to get an fstream object and open the file in “ios::in” and “ios::out” mode.

Читайте также:  Javascript get запрос параметры

In this example, we first write some content to the file. Then, we read the data from the file and print it to the monitor.

int main ( )

fstream myFile_Handler ;
string myLine ;

// File Open
myFile_Handler. open ( «File_1.txt» , ios :: in

myFile_Handler. seekg ( ios :: beg ) ;

// Read the File
if ( myFile_Handler. is_open ( ) )
{
// Keep reading the file
while ( getline ( myFile_Handler, myLine ) )
{
// print the line on the standard output
cout }

// File Close
myFile_Handler. close ( ) ;
}
else
{
cout }
myFile_Handler. close ( ) ;
return 0 ;
}

Now, we will compile and execute the program.

Example 5: Read and Write to a Binary File

In this example, we are going to declare a class and then write the object to a binary file. To simplify this example, we have declared the Employee class with a public variable emp_id. Then, we will read the binary file and print the output to the monitor.

class Employee
{
public :
int emp_id ;
} ;

int main ( )

ofstream binOutFile_Handler ;
ifstream binInFile_Handler ;

Employee empObj_W, empObj_R ;

// File Open
binOutFile_Handler. open ( «Employee.dat» , ios :: out

// Initialize empObj_W
empObj_W. emp_id = 1512 ;

// Write to the file
binOutFile_Handler. write ( ( char * ) & empObj_W, sizeof ( Employee ) ) ;
binOutFile_Handler. close ( ) ;

// Now, let’s read the employee.dat file
binInFile_Handler. open ( «Employee.dat» , ios :: in | ios :: binary ) ;
// Check if the file has opened
if ( ! binInFile_Handler )
{
cout exit ( 3 ) ;
}

// Read the content of the binary file
binInFile_Handler. read ( ( char * ) & empObj_R, sizeof ( Employee ) ) ;
binInFile_Handler. close ( ) ;

Conclusion

Files are mainly used to store the data, and they play an important role in real-world programming. In this article, we showed you how to use various file operations with the C++ programming language by working through several examples. Furthermore, we showed you how to read and write data into both text files and binary files.

About the author

Sukumar Paul

I am a passionate software engineer and blogger. I have done my Masters in Software Engineering from BITS PILANI University, India. I have very good experience in real-time software development and testing using C, C++, and Python. Follow me at thecloudstrap.com.

Источник

Оцените статью