3 An example

Let us explore an example of file read. The subroutine readnums opens a file, reads the number in the file into an array, then returns. Listing 1 is the first trial.


Listing 1:readnums.1
 
1unsigned readnums(const char *path, int array[], unsigned n) 
2{ 
3  // read up to n integers from the file at path 
4  ifstream file; 
5  unsigned i; 
6 
7  file.open(path);   
8  i = 0; 
9  while (!file.eof() && (i < n)) 
10  { 
11    file >> array[i];  
12  } 
13  file.close();  
14  return i; 
15}

The first version readnums is quite simple, but it lacks many error detection and handling logic. Let us see how we can improve it.

 3.1 Potential errors
 3.2 Throw exceptions
 3.3 Calling readnums
 3.4 Try and catch