How to Read and Write Arrays to/from Files in C++?
Last Updated :
11 Mar, 2024
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++
#include <fstream>
#include <iostream>
using namespace std;
int main()
{
int arr[] = { 1, 2, 3, 4, 5 };
int size = sizeof (arr) / sizeof (arr[0]);
ofstream outfile( "array.txt" );
if (!outfile.is_open()) {
cerr << "Failed to open file for writing.\n" ;
return 1;
}
for ( int i = 0; i < size; ++i) {
outfile << arr[i] << " " ;
}
outfile.close();
ifstream infile( "array.txt" );
for ( int i = 0; i < size; ++i) {
infile >> arr[i];
}
infile.close();
cout << "Array elements: " ;
for ( int i = 0; i < 5; ++i) {
cout << arr[i] << " " ;
}
cout << endl;
return 0;
}
|
Output
Array elements: 1 2 3 4 5
Time Complexity: O(N), here N is the size of the array.
Auxiliary Space: O(1)
Share your thoughts in the comments
Please Login to comment...