Computer Science 301 - 2001


Tutorial for week 16 - File handling and stack machine coding

(a) How does one open files safely in C/C++?

(b) What do you suppose underlies the FILE * type imported from stdio.h?

(c) What do you suppose happens if you try to read from or write to non-existent files or devices?

(d) What happens if you do not explicitly close files that you have opened?

(e) Develop stack machine code equivalents of the following simple programs:

(1)  PROGRAM One;
       VAR
         I, J;
       BEGIN
         Read(I, J); Write(I + J)
       END.


(2)  PROGRAM Two;
       VAR
         I, J;
       BEGIN
         Read(I, J);
         J := (2 * I + J) / 2
       END.


(3)  PROGRAM Three;
       VAR
         I, J;
       BEGIN
         Read(I, J);
         IF I > J THEN Write(I, ' is larger than ', J);
         Write('Difference is', I - J)
       END.


(4)  void main () {
       for (int i = 0; i <= 10; i++) printf("%d\n", i)
     }


(5)  void main () {
       int i, list[11];
       i = 0;
       while (i <= 10) {
         list[i] = 2 * i;
         i++;
       }
     }

(6)  PROGRAM Six;
       VAR
         List[10], I, J;
       BEGIN
         Read(I, J, List[I+J]);
         List[List[J]] := List[J + 2 * I]
       END.


(7)  void main () {
     // You might like to predict the output of this program first (in other
     // words - do you really understand its dynamic semantics?)
       int i, list[20];
       for (i = 0; i <= 10; list[++i] = i);
       for (i = 0; i <= 10; printf("%d %d ", i, list[i++]);
     }