Read file into array in C++

C++ read file into array

C++ is a powerful language that provides us with ways to read the data from files and write the data back to them. Files are a way of permanently storing the data on the disk so that data is not lost when the execution of the program ends. Often we need to retrieve data from disk to process them in our programs. In this article, we will discuss how to read file into array in C++.

How to declare an array in C++?

Before discussing the code, let us have a look at how arrays work in C++.

Arrays in C++ are contiguous memory locations under one name.  We use arrays to store related data with the same data type together under one name. In C++, we define an array using the following syntax.

For example, we will use the following statement to create an array named myArr that can store five elements of the string data type.

After defining the array, we can access elements from the array using their indices. Arrays in C++ are indexed using 0 based indexing. It means that the first element has an index 0, the second element has index 1, the third element has an index 2, and so on. The last element in an array with size N has the index (N-1).

How To Open A File in C++?

Files are used to permanently store the data on the disk. The data in the main memory is volatile and can not be retained forever. Once you close the program, the data of the program is cleared from the main memory so that other programs can use the memory space. Therefore files are needed to store the data in the storage devices for a longer time. C++ provides a simple and efficient way to read and write the data into the files. We will now explore the different libraries and their methods to perform the file operations in C++.

C++ Libraries For File Handling

C++ provides three libraries to perform the file operations such as opening a file, reading a file, and writing to a file.

  1. ofstream: You can use this library to write to a file in C++. For this,  you can include the ofstream library in your program to write data into a file.
  2. ifstream: You can use this library to read data from a file in C++. For this, you can include the ifstream library in your program to perform file read operations.
  3. fstream: You can use this library to perform both the read and write operation on a file in C++. For this, you can include the fstream library to perform all the file operations in your program.

Opening File in C++

You can open a file in C++ in two ways. Either, you can open the file while declaring the file stream object by passing the filename as an input argument to the constructor. Or, you can open the file after creating the file stream object by using the open() method. Let us discuss both ways to open a file in C++ one by one.

Open A File in C++ By Passing Filename To File Stream Constructor As Parameter

In this section, we will discuss the syntax for opening a file using different libraries in C++ while creating a file stream object.

You can open a file using the ifstream library in C++ using the following syntax.

Here, the file is opened only for read operations. The parameters of the constructor are given as follows:

  • filename: a string that represents the name of the file to be opened.
  • mode: flag(s) representing the i/o mode for the opened file.

You can observe that the default value for mode has already been described as ios_base::in i.e. input mode. So, to open a file, you just have to pass the filename to the ifstream constructor as follows.

Alternatively, you can use the ofstream library to open a file in C++ while declaring the file stream object using the following syntax.

The ofstream constructor is used to open the file in write mode. The parameters are same as given for the ifstream constructor. However, we have changed the default value for mode to ios_base::out. It means that the file will be opened in write mode. Again, you can open a file in write mode using the ofstream library by simply passing the filename to the ofstream constructor as follows.

Another way to open a file in C++ is by using the fstream library. Here, we will open the file in read and write mode. So, we pass both the values ios_base::in and ios_base::out as the default value for mode as shown below.

The fstream library opens the file in read as well as write mode. Again, you can open the file in read and write mode in C++ by simply passing the filename to the fstream constructor as follows.

Open A File in C++ Using The open() Function

Instead of passing the filename to constructors of the file stream object, you can use the open() method to open a file in C++. The syntax for using the open() method in the libraries is as follows.

  1. ifstream_object.open(const char* filename, ios_base::openmode mode = ios_base::in);
  2. ofstream_object.open(const char* filename, ios_base::openmode mode = ios_base::out);
  3. fstream_object.open (const char* filename, ios_base::openmode mode = ios_base::in | ios_base::out);

The open() function takes parameters similar to those defined in the constructor. The meaning of parameters also remains the same.

Till now, we have discussed how we can use files and arrays. Let us now discuss the program to read a file into an array in C++.

Program To Read File Into Array In C++

In the following program, we have defined an array of size 100000. After that, we have read the file into an array using the fstream library in C++. You can observe that we have read the file line by line and then we have stored it in the array. Although comments are given, we have explained the program line by line after the output for your better understanding.

The sample text file used in this program is as follows.

Hello, this is a sample program.
This reads file to array.
Each line is a different array element.

Output:

Enter filename:sample.txt 
Hello, this is a sample program.
This reads file to array.
Each line is a different array element.

It is clearly visible that each line in the file has been read and kept to an array which is then displayed as the output.

Explanation For The Code

First, we have included  the following header files that have been used in the program.

  • iostream: It has been used for input output operations.
  • fstream: It has been used for file operations.
  • string: It has been used so that we can use string variables in the program.

After including the header files, the SIZE variable has been used to declare the size of the array in which the file will be read. Since arrays are of fixed size, we have declared an array of large size so that the file data can be put into the array without overflowing. 

Then, we have used the cout statement to prompt the user to input the name of the file that is to be read. Be careful to provide the complete path if the file does not exist in the same folder where the code file is kept. The filename has been read using the cin statement. Then, we have declared a string variable line to read each line from the file, an integer i to keep count of lines, and an array named arr of strings to store each line that has been read from the file.

Then we have used the ifstream constructor to create a file stream object to read the file. We have passed the filename that has to be opened while creating a file stream object named mFile. The default open mode is input mode. 

The next line checks if the file has been opened successfully, failing which an appropriate message is displayed in the else part of the condition stating that the program couldn’t open the file.

In the while loop, !mFile.eof() checks if the end of the file is reached or not. In the loop, we retrieve a line from the file and put it into the array. Each time we increase the current array index by 1 (the i variable). This process is repeated until the program reaches the end of the file. 

Finally,  the array contents are displayed with the help of a for loop.

Takeaways

C++ is a powerful language with multiple functionalities to perform various tasks. You can perform different file operations very efficiently in C++ using the inbuilt libraries. In this article, we have discussed the basics of how to open a file in C++ in different modes. Then, we discussed a program to read a file into an array in C++. For this, we have read the input from the file line by line and kept each line into an array as a separate element. You can use the concepts discussed in the program to write better code for your applications.

I hope you had a fun time reading this blog. 

Happy Learning!


import_contacts

You may also like:

Related Posts

  • Split String by comma in C++
    10 November

    Split String by comma in C++

    Table of ContentsUsing the for loopUsing the getline() functionUsing the strtok() functionUsing the std::string::erase() and std::string::find() function In this article, we will split a string by comma in C++. There are several methods available to achieve this. For this, we can create a function and use some inbuilt functions. Using the for loop In this […]

  • C++ wait seconds
    06 November

    How to wait for seconds in C++?

    Table of ContentsWait For Seconds Using The sleep () Function in C++Wait For Seconds Using Thread In C++Wait for seconds using sleep_for() function in C++Wait for seconds using sleep_until() function in C++Wait for seconds using delay() function in C++Wait for seconds using the wait() function in CWait For Seconds Using Timer in C++Conclusion There are […]

  • C++ copy array
    06 November

    Copy Array in C++

    Table of ContentsShallow Copy And Deep Copy In C++How To Copy Array Elements Using Library Functions in C++?How To Copy Array Elements Using The copy() Function in C++?How To Copy Array Elements Using The copy_n() Function in C++?How To Copy Array Elements Using The copy_if() Function in C++?How To Copy Array Elements Using The copy_backward() […]

  • Read CSV file in C++
    01 November

    How to read CSV file in C++?

    Table of ContentsWhat is a CSV File? How To Read A CSV File In C++?C++ Code To Read A CSV FileHow To Read A CSV File Using C-Based Approach?Conclusion CSV files or Comma Separated Value Files are simple yet special files that we use to store data. Here, each value is separated by a comma, and […]

  • Count lines in file in C++
    01 November

    Count lines in file in C++

    Table of ContentsHow To Count Lines In A File In C++?C++ Program To Count Lines In A FileHow To Count Lines In A File In C++ Using C-style Approach?C++ Program to Count Lines In A File using C-style approachConclusion We often store our data into files when we need the data to be persistent and […]

  • Get Number of Elements in Array in C++
    08 October

    Get Number of Elements in Array in C++

    Table of ContentsGet Number of Elements in Array in C++Using the sizeof() functionUsing the pointersUsing the size() functionGet the frequency of each element in array in C++Using nested for loopUsing maps One of the most fundamental collections in any programming language is an array. It stores a similar type of data at specific indices that […]

Leave a Reply

Your email address will not be published. Required fields are marked *

Subscribe to our newletter

Get quality tutorials to your inbox. Subscribe now.