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::ifstream
for 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++.
// C++ program to demonstrate how to read and write arrays to/from files #include <fstream> #include <iostream> using namespace std;
int main()
{ // Creating an array of size 5
int arr[] = { 1, 2, 3, 4, 5 };
int size = sizeof (arr) / sizeof (arr[0]);
// Opening the file in write mode
ofstream outfile( "array.txt" );
if (!outfile.is_open()) {
cerr << "Failed to open file for writing.\n" ;
return 1;
}
// Writing the array elements to the file
for ( int i = 0; i < size; ++i) {
outfile << arr[i] << " " ;
}
// Closing the file
outfile.close();
// Opening the file in read mode
ifstream infile( "array.txt" );
// Reading the array elements from the file
for ( int i = 0; i < size; ++i) {
infile >> arr[i];
}
// Closing the file
infile.close();
// Displaying the array elements
cout << "Array elements: " ;
for ( int i = 0; i < 5; ++i) {
cout << arr[i] << " " ;
}
cout << endl;
return 0;
} |
Array elements: 1 2 3 4 5
Time Complexity: O(N), here N is the size of the array.
Auxiliary Space: O(1)