Reading a File into an Array using C++
Posted by Samath
Last Updated: January 04, 2017
  473

In this C++ program we are reading "items.txt" file character by character and saving it in an array until end of file character reached in the file. After that we display the array using a for loop. the code is provided below.

Code:

#include <iostream> 
#include <fstream>  
using namespace std;

int main()
{
  int array_size = 1024; 
	char * array = new char[array_size];
	int position = 0; 
  
	ifstream fin("items.txt");
  if(fin.is_open())
	{
    cout << "File Opened successfully!!!. Reading data from file into array" << endl;
		while(!fin.eof() && position < array_size)
		{
			fin.get(array[position]); 
			position++;
		}
		array[position-1] = '\0';
    
    cout << "Displaying Array..." << endl << endl; 
		for(int i = 0; array[i] != '\0'; i++)
		{
			cout << array[i];
		}
	}
	else 
	{
		cout << "File could not be opened." << endl;
	}
	return 0;
}