CMPT
130 Lab 9 - Files
In this lab
you are going to write two functions, one read from a file and one to write to
a file. There are functions in the presentation
on files that would make good starting points for these functions – feel free
to use them.
Labs are assessed, so make sure that the TA has seen, and marked,
your finished work before you leave the lab.
Read File
Data
Write
a function that reads a file of integers and returns a pointer to an array (in
dynamic memory) that contains those integers. The function should have two
parameters, a string parameter that stores the name of the file to be read, and
an integer reference parameter that is used to store the size of the array.
File Format
The
file is intended to contain integer data. The first value in the file contains
the number of integers in the file. Note that this structure is identical to
the example in the presentation. You can therefore use the last function in the
presentation with no changes to perform this task.
Write
Sequences
Write
a void function that has an integer array parameter and a second integer
parameter that holds the size of the array. The function should prompt the user
to enter the name of the file to be created.
Getting
the name of the output file is the same as getting any other input. Prompt the
user to enter the name and then store what they enter in a variable of an
appropriate type. In this case the type will be a string. The only extra step to make this work is to include the
string library.
The
function should then write a list of descending sequences to this file, one
sequence per line, with sequence values separated by spaces. A sequence should
be written for each value in the array parameter. The sequences should start
with the array value and count down to 1 (i.e. n, n-1, n-2, …, 2, 1 if the array value is n) . Array
values less than 1 should be ignored. See the example given below. Hint: you
will need a nested loop.
Example
Let's
assume that the array parameter contains the following values.
7
12
-11
5
10
0
3
The resulting
file should therefore contain this data.
7 6 5 4 3 2 1
12 11 10 9 8 7 6 5 4 3 2 1
5 4 3 2 1
10 9 8 7 6 5 4 3 2 1
3 2 1
Main
Function
Call
your two functions to read this file and write a
sequence for each of the numbers contained therein to an output file. Note that
you will have to copy the input file to the directory containing your .cpp file to successfully read it.
Assessment
1 mark for
completion of the lab.
John Edgar (johnwill@sfu.ca)