08.01.2023 Views

Learn to Program with C_ Learn to Program using the Popular C Programming Language ( PDFDrive )

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 8 ■ Arrays

If in is NULL, the program prints a message and stops. If in is not NULL, the program proceeds

as before.

The predefined function exit is used to terminate execution of a program and return control

to the operating system. It is conventional to use exit(0) to indicate normal termination; other

arguments are used to indicate some sort of error.

To use exit, we must write the directive

#include <stdlib.h>

at the head of our program, since exit is defined in the “standard library,” stdlib.h. Among other

things, this library contains functions for working with random numbers, functions for searching,

and functions for sorting.

As usual, we can assign a value to in and test it for NULL, using the following:

FILE * in;

if ((in = fopen("passage.txt", "r")) == NULL) {

printf("File cannot be found\n");

exit(1);

}

Note that we cannot use FILE * in in the if condition, since a declaration is not

permitted there.

Similarly, when we write

FILE * out = fopen("output.txt", "w");

we are assuming that the file output.txt exists or can be created. If it does not exist and cannot

be created (the disk may be write protected or full, for instance), fopen will return NULL. We can

test for this as follows:

FILE * out;

if ((out = fopen("output.txt", "w")) == NULL) {

printf("File cannot be found or created\n");

exit(1);

}

So far, we have written the name of our file in the fopen statement. To use a different file,

we would have to change the name in the statement, and we would have to re-compile the

program. Our program would be more flexible if we let the user tell us the name of the file when

the program is run.

We can declare dataFile (say) to hold the name of the file with

char dataFile[40];

210

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!