Read File Into Array or ArrayList in C++/Java

On this entry we cover a question that appears a lot on the boards in a variety of languages. Reading lines of a file into an array, vector or arraylist. I have several examples lined up for you to show you some of the ways you can accomplish this in C++ as well as Java. Keep in mind that these examples are very simplistic in nature and designed to be a skeleton which you can take apart and use in your own stuff. So feel free to hack them apart, throw away what you don’t need and add in whatever you want. As with all code here it is in the public domain. Now lets cover file reading and putting it into an array/vector/arraylist…. right here on the Programming Underground!

The process of reading a file and storing it into an array, vector or arraylist is pretty simple once you know the pieces involved. The pieces you are going to need is a mechanism for reading each line of a file (or each word or each token etc), a way to determine when you have reached the end of the file (or when to stop), and then an array or arraylist to actually hold the values you read in.

For our examples below they come in two flavors. One is reading a certain number of lines from the file and putting it into an array of known size. These examples would be for those projects where you know how many lines are in the file and it won’t change or the file has more lines but you only want X number of lines.

If you know the number of lines you want to read, using an array is going to be the ideal choice because arrays are simple, can have a fixed length and are relatively fast compared to some reference type objects like an arraylist.

The second flavor is for when you don’t know how many lines you want to read, you want to read all lines, want to read lines until a condition is true, or want something that can grow and shrink over time. These examples involve using a more flexible object oriented approach like a vector (C++) or an arraylist (Java). With these objects you don’t need to know how many lines are in the file and they will expand, or in some instances contract, with the items it contains.

Lets take a look at two examples of the first flavor. Below is an example of a C++ program that reads in a 4 line file called “input.txt” and puts it in an array of 4 length. Remember indexes of arrays start at zero so you have subscripts 0-3 to work with. After that is an example of a Java program which also controls the limit of read in lines and places them into an array of strings.

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

// Define a constant for the number of lines to read
#define NUM_READ_LINES 4

int main() {
	// Array of line numbers each line being no more than 100 chars
	char thearray[NUM_READ_LINES][100];
	int counter = 0;

	// Open our file
	ifstream inFile("c:\\input.txt",ifstream::in);

	// If we can read/write great
	if (inFile.good()) {

		// Read throuthe file and load into array
		while (!inFile.eof() && (counter < NUM_READ_LINES)) {
			inFile.getline(thearray[counter],100);
			counter++;
		}

		// Loop through the array which we just put together
		for (int i = 0; i < counter; i++) {
			cout << thearray[i] << endl;
		}
	}

	inFile.close();	

	return 0;
}

As with all the code here on the Programming Underground the in-code comments will help guide your way through the program. Here we start off by defining a constant which will represent the number of lines to read. We use a constant so that we can change this number in one location and everywhere else in the code it will use this number instead of having to change it in multiple spots. Smart design idea right? 😉

We then open our file using an ifstream object (from the include) and check if the file is good for I/O operations. If so, we go into a loop where we use getline() method of ifstream to read each line up to 100 characters or hit a new line character. Notice here that we put the line directly into a 2D array where the first dimension is the number of lines and the second dimension also matches the number of characters designated to each line. This is saying for each entry of the array, allow us to store up to 100 characters.

If your lines are longer than 100, simply bump up the 100… or better yet also make it a constant that can be changed. Getline will read up to the newline character by default ‘\n’ or 100 characters, whichever comes first. So if you have long lines, bump up the number to make sure you get the entire line.

The loop will continue while we don’t hit the EOF or we don’t exceed our line limit. To determine the line limit we use a simple line counting system using a counter variable. You might ask “Why not use a for loop then?” well the reason I chose a while loop here is that I want to be able to easily detect the end of the file just in case it is less than 4 lines. If we had used an for loop we would have to detect the EOF in the for loop and prematurely break out which might have been a little ugly. At least this way we can control the loop and check its conditions each iteration without having to introduce another if statement or anything inside the loop.

Once we have read in all the lines and the array is full, we simply loop back through the array (using the counter from the first loop) and print out all the items to see if they were read in successfully. From here you could add in your own code to do whatever you want with those lines in the array.

Below is the same style of program but for Java.

import java.io.*;

public class readIntoArray {
	public static void main(String args[]) {
		// Create an array of 4 strings (indexes 0 - 3)
		String arrayOfStrings[] = new String[4];
		
		try {
			// Create a bufferreader object to read our file with.
			BufferedReader reader = new BufferedReader(new FileReader("c:\\input.txt"));
			
			// Line will hold our line read from the file
			String line = "";
			
			// The counter will keep track of how many lines we have read
			int counter = 0;
			
			// Read in a line from the file and store it in "line". Do this while we don't hit null or while the counter is less than 4.
			// The counter prevents us from reading in too many lines.
			while (((line = reader.readLine()) != null) && (counter < 4)) {
				arrayOfStrings[counter] = line;
				counter++;
			}
			
			// With a foreach style loop we loop through the array of strings and print them out to show they were read in.
			for (String readline : arrayOfStrings) {
				System.out.println(readline);
			}
			
			reader.close();
		}
		catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); }
	}
}

With Java we setup our program to create an array of strings and then open our file using a bufferedreader object. You will also notice that the while loop is very similar to the one we say in the C++ example. We read in each line from our bufferedreader object using readLine and store it in our variable called “line”. We will keep doing this until it is null (meaning we hit the end of file) or the counter is less than our line limit of 4.

Each line we read we put in the array and increment the counter. Lastly we use a foreach style loop to print out the value of each subscript in the array. All this has been wrapped in a try catch statement in case there were any thrown exception errors from the file handling functions.

As mentioned towards the beginning of this entry, these first two programs represent the first flavor of reading a limited number of lines into a fixed length structure of X elements. The second flavor is using objects which keep track of a collection of items, thus they can grow and shrink as necessary with the items we add and remove. They are flexible. In C++ we use the vector object which keeps a collection of strings read from the file. Instead of dumping straight into the vector, we use the push_back() method to “push” the items onto the vector.

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

int main() {
	// Open our file
	ifstream inFile("c:\\input.txt",ifstream::in);

	// If we can read/write great
	if (inFile.good()) {

		// Create a vector of strings
		std::vector<string> strVector;

		// Create a string variable to hold each line read from the file.
		string line;

		// Read throuthe file and push onto our vector
		while (!inFile.eof()) {
			getline(inFile,line);
			strVector.push_back(line);
		}

		// Create a vector iterator
		vector<string>::iterator it;

		// Loop through the vector from start to end and print out the string
		// the iterator is pointing to.
		for (it = strVector.begin(); it < strVector.end(); it++) {
			cout << *it << endl;
		}

	}

	inFile.close();
	return 0;
}

As you will notice this program simplifies several things including getting rid of the need for a counter and a little bit crazy while loop condition. Here we can freely read our file, like the first example, but have the while loop continue until it hits the end of file. Each line is read using a getline() general function (notice it is not used as a method of inFile here but inFile is passed to it instead) and stored in our string variable called “line”. Line is then pushed onto the vector called strVector using the push_back() method.

The tricky part is next where we setup a vector iterator. I am not going to go into iterators too much here but the idea of an iterator can be thought of as a pointer to an active current record of our collection. So our for loop sets it at the beginning of the vector and keeps iteratoring until it reaches the end. We can advance the iterator one spot using a simple increment.

Keep in mind that an iterator is a “pointer” to the current item, it is not the current item itself. So in order to get at the value of the pointer we have to dereference it before printing which we do using the asterisk.

In java we can use an arraylist object to pretty much do the same thing as a vector in C++. We create an arraylist of strings and then loop through the items as a collection.

import java.util.ArrayList;
import java.io.*;

public class readIntoArray2 {
	public static void main(String args[]) {
		// Lets create an arrayList object full of String types.
		ArrayList<String> arrayOfStrings = new ArrayList<String>();
		
		try {
			// Create our bufferedreader to read the file
			BufferedReader reader = new BufferedReader(new FileReader("c:\\input.txt"));
			
			// Line to hold the line read from file
			String line = "";
			
			// Loop through the file reading in lines and storing in "line". Do this until readLine returns null (end of file)
			// Add each line to our arraylist object
			while ((line = reader.readLine()) != null) {
				arrayOfStrings.add(line);
			}
			
			// Now use a foreach style loop to read each string in our arraylist. Notice we don't have to cast
			// to string because we told the arraylist that it will hold strings at the start.
			for (String readline : arrayOfStrings) {
				System.out.println(readline);
			}
			
			reader.close();
		}
		catch (Exception ex) { System.out.println("Exception: " + ex.getMessage()); }
	}
}

Again you will notice that it starts out like the first Java example, but instead of a string array we create an arraylist of strings. The while loop is also greatly simplified here too since we no longer have to keep track of the count. We can keep reading and adding each line to the arraylist until we hit the end of the file. We add each line to the arraylist using its “add” method. Just like using push_back() in the C++ version.

Then once more we use a foreach style loop to iterate through the arraylist. Each item of the arraylist does not need casting to a string because we told the arraylist at the start that it would be holding strings. If we had not done that, each item in the arraylist would have been stored as an object and we might have had to cast it back to a string before we could use it. So keep that in mind if you are using custom objects or any object that is not a simple string.

So that is all there is to it. Four separate programs covering two different methods for reading a file and dumping it into two separate structure types. Again you can use these little examples to build on and form your own programs with. You could also use these programs to just read a file line by line without dumping it into a structure. Perhaps you can use them to create the basic fundamental search of a file utility. The choice is yours.

🙂

About The Author

Martyr2 is the founder of the Coders Lexicon and author of the new ebooks "The Programmers Idea Book" and "Diagnosing the Problem" . He has been a programmer for over 20 years. He works for a hot application development company in Vancouver Canada which service some of the biggest tech companies in the world. He has won numerous awards for his mentoring in software development and contributes regularly to several communities around the web. He is an expert in numerous languages including .NET, PHP, C/C++, Java and more.