20.3: Loading an Array from a File
- Page ID
Loading an array from a file presents an interesting dilemma. The problem resolves around how many elements you should plan for in the array. Let’s say 100, but what if the file has fewer or more than 100 values. How can the program handle it correctly?
The solution involves some simple steps:
- We can read the file once to get the element count. Thus, we will know exactly how many members (elements) we will need.
- We can then create an array using dynamic memory allocation by defining the array within a function so that it has local scope. Local scope variables are created during the execution of the program and use the stack as the storage location instead of the data area. If you define the array outside of a function (global scope also known as static memory allocation) it stores it in the data area and must know how much storage space to allocate to the array when you write the source code. Since we don’t know how many elements will be on the input file when we write the source code defining an array with global scope will not work. But, we can determine exactly how many members we need for the array by having our program count them (step 1) so that we can then define the array with local scope to the precise size needed.
- We can then load the array by reading the file a second time and storing the values read into the array just created.
This method is demonstrated in the demo file provided, thus you need to study this material in conjunction with the demo program.
Demonstration Program in C++
Creating a Folder or Sub-Folder for Source Code Files
Depending on your compiler/IDE, you should decide where to download and store source code files for processing. Prudence dictates that you create these folders as needed prior to downloading source code files. A suggested sub-folder for the Bloodshed Dev-C++ 5 compiler/IDE might be named:
If you have not done so, please create the folder(s) and/or sub-folder(s) as appropriate.
Download the Demo Program
Download and store the following file(s) to your storage device in the appropriate folder(s). Following the methods of your compiler/IDE, compile and run the program(s). Study the source code file(s) in conjunction with other learning materials. You may need to right click on the link and select "Save Target As" in order to download the file.
Download from Connexions: Demo_Loading_Array_from_File.cpp
Download from Connexions: Demo_Farm_Acres_Input.txt
- Dynamic Memory
- Aka stack created memory associated with local scope.
- Static Memory
- Aka data area memory associated with global scope.