C++

Read a File into an Array in C++

Reading the whole file into an array is not as difficult as it may sound. A file, whether text or otherwise, consists of bytes from the beginning to end. The bytes can be read as characters. The characters can be read one-by-one into the array.

This article explains how to read a whole file into an array. The C++ header (library) fstream, has the class ifstream. The class ifstream has get() overloaded member functions. Two of these overloaded member functions can be used to read the whole file into an array. A Program for such reading should begin with:

#include <fstream>

#include <iostream>

using namespace std;

The first two lines are directives, not statements. The first one includes the fstream library for the get() functions. The second one includes the iostream library for printing to the terminal (console) and for receiving characters from the keyboard. The third line is a statement. It insists that any name not preceded by “std::” is of the standard namespace.

There is a small issue with the get() functions, the array length has to be estimated, to be at least one character more than the number of characters in the file. The idea is to have ‘\0’ included just after the last read character in the array would form one long string.

If the length of the array cannot be estimated as such, then the whole file has to be read into some other object such as a string object (of the string class). Since the aim of this article is to explain how to read into an array, then the array size has to be estimated.

For the rest of this article, it is assumed that the name of the file, whose content is to be read, is txtFile.txt, in the directory, dir1, in the home/user directory.

Article Content

– Reading Whole File Character-by-Character

– Reading Whole File with one Member Function

– Conclusion

Reading Whole File Character-by-Character

The syntax of the ifstream overloaded get() function, for this, is:

basic_istream<charT, traits>& get(char_type& c);

A program code segment to read the next character in the file, is:

        char c;
        char arr[100];
        int i = 0;
        while (ifs.get(c)) {
arr[i] = c;
i++;
        }

The first statement declares the variable, c will receive each of the characters. The second statement declares the array that will receive all the characters, one by one. The third line declares an index for the array beginning from zero for addressing all the elements of the array, that will receive a character. With this approach, ‘\0’ can be added after the last character of the file has been included into the array.

The parentheses of the while-loop has,

ifs.get(c)

where ifs is the name of the ifstream object. The next character of the file is gotten by the get member function and assigned to c. After this, the internal pointer of the ifstream object would point to the character after the one read. When the end-of-file is reached, the expression, “ifs.get(c)” becomes false instead of true and so the while-loop ends.

The following program, will read all the characters of a file and print out all the content to the terminal:

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

    int main()
    {
ifstream ifs = ifstream("dir1/txtFile.txt", ios_base::in);
        if (ifs.is_open() == true) {
            char c; int i = 0; char arr[100];
            while (ifs.get(c)) {
arr[i] = c;
i++;
            }
ifs.close(); arr[i] = '\0'; cout<<arr<<endl;
        }
        else
cout<< "File could not be open!" <<endl;

        return 0;
    }

ifstream as coded, opens the file for reading.

Reading Whole File with one Member Function

The ifstream overloaded get() member function to read the whole file, without the while loop, is:

basic_istream<charT, traits>& get(char_type* s, streamsize n, char_type delim);

It still reads the whole file character-by-character but that is no longer the business of the C++ programmer. Also, this function adds the null character, ‘\0’ on behalf of the programmer, assuming that n is at least one character longer than the content of the file.

The first argument of this overloaded get() function is the array with the same constraints (including estimation) as the above array to receive all the characters of the file. The second argument, n, of streamsize type is an estimate of the number of characters in the file. It is advisable to make the size of the array and n, the same. There is no need for a while-loop with this member function.

Now, a line in a text file ends with the escape sequence, ‘\n’. If the third argument is ‘\n’, then only the first line of the file would be read. So, the function has to be deceived with any character that is not likely to be found in the file’s content. A good candidate for the third argument, is ‘\0’. With this overloaded member function, the programmer needs to have some knowledge of the possible characters in the file so as not to use a character which is part of the content of the file.

The following program will read all the characters of a file with one statement and print out all the content to the terminal:

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

    int main()
    {
ifstream ifs = ifstream("dir1/txtFile.txt", ios_base::in);
        if (ifs.is_open() == true) {
            char arr[100];
ifs.get(arr, 100, '\0');
ifs.close(); cout<<arr<<endl;
        }
        else
cout<< "File could not be open!" <<endl;

        return 0;
    }

Conclusion

A whole file can be read into an array. This first of all needs the C++ ifstream class of the fstream library. The file has to be opened for reading. To read all the characters (bytes) of a file (one by one) into the array use the ifstream member function,

basic_istream<charT, traits>& get(char_type& c)

as the condition in a while-loop. To read all the characters (bytes) of a file, into the array with one ifstream member function without the while-loop, the ifstream member function should be:

basic_istream<charT, traits>& get(char_type* s, streamsize n, char_type delim);

Do not forget to trick the function at the third argument. With this function, the programmer needs to have some knowledge of the possible characters in the file.

About the author

Chrysanthus Forcha

Discoverer of mathematics Integration from First Principles and related series. Master’s Degree in Technical Education, specializing in Electronics and Computer Software. BSc Electronics. I also have knowledge and experience at the Master’s level in Computing and Telecommunications. Out of 20,000 writers, I was the 37th best writer at devarticles.com. I have been working in these fields for more than 10 years.