C Programming

prev next

Practise Exercise 9A: File Handling

1. The statement that defines an input file handle called input_file, which is a pointer to type FILE, is

type input_file as FILE;
FILE *input_file;
input_file FILE;
*FILE input_file;

2. Using input_file, open the file results.dat for read mode.

input_file = "results.dat" opened as "r";
open input_file as "results.dat" for "r";
fopen( input_file, "results.dat", "r" );
input_file = fopen( "results.dat", "r" );

3. Write C statements which tests to see if input_file has opened the data file successfully. If not, print an error message and exit the program.

Test 1

	if( input_file == NULL ) {
		printf("Unable to open file.\n");\
		exit(1);
	}
Test 2

	if( input_file != NULL ) {
		printf("Unable to open file.\n");\
		exit(1);
	}
Test 3

	while( input_file = NULL ) {
		printf("Unable to open file.\n");\
		exit(1);
	}

4. Write C code which will read a line of characters (terminated by a \n) from input_file into a character array called buffer. NULL terminate the buffer upon reading a \n.

Example 1

	int ch, loop = 0;

	ch = fgetc( input_file );
	while( (ch != '\n') && (ch != EOF) ) {
		buffer[loop] = ch;
		loop++;
		ch = fgetc( input_file );
	}
	buffer[loop] = NULL;
Example 2

	int ch, loop = 0;

	ch = fgetc( input_file );
	while( (ch = '\n') && (ch = EOF) ) {
		buffer[loop] = ch;
		loop--;
		ch = fgetc( input_file );
	}
	buffer[loop] = NULL;
Example 3

	int ch, loop = 0;

	ch = fgetc( input_file );
	while( (ch <> '\n') && (ch != EOF) ) {
		buffer[loop] = ch;
		loop++;
		ch = fgetc( input_file );
	}
	buffer[loop] = -1;

5. Close the file associated with input_file.

close input_file;
fclose( input_file );
fcloseall();
input_file( fclose );

©Copyright B Brown. 1984-1999. All rights reserved.
prev next