VOOZH about

URL: https://www.geeksforgeeks.org/cpp/how-to-read-and-write-arrays-to-and-from-files-in-cpp/

⇱ How to Read and Write Arrays to/from Files in C++? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Read and Write Arrays to/from Files in C++?

Last Updated : 23 Jul, 2025

In C++, an array is a collection of elements of the same type placed in contiguous memory locations. A file is a container in a computer system for storing information. In this article, we will learn how to read and write arrays to/from files in C++.

Example:

Input: 
Array = {1, 2, 3, 4, 5}
Output:
// Write the array to a file, then read the array from the file
Array: 1 2 3 4 5

Reading and Writing Arrays to and from Files in C++

To read and write arrays to and from files in C++, we can use the file streams from the standard library, std::ifstreamfor reading from files and std::ofstream for writing to files. We can read and write the arrays in a similar way as any other data.

C++ Program to Read and Write Arrays to and from Files

The below example demonstrates how to read and write arrays to/from files in C++.


Output
Array elements: 1 2 3 4 5 

Time Complexity: O(N), here N is the size of the array.
Auxiliary Space: O(1)



Comment