Next: File output Up: Input-Output Previous: Files

Getting access to a file

To do this it is necessary to open the file. As it is possible to have several files open at once, you need some means of saying which file you want to deal with at any given instant. C uses a data structure for file management: you need a pointer to the structure, but you do not need to know what the structure contains.

	FILE *fp;	/* create a file pointer */

	FILE *fopen();

Now you can open the file:

	fp= fopen(name, mode);

In general name is a string giving the actual name of the file. mode is a string saying how you want to use the file. The mode string should contain r,w,a in the desired combination:

If an existing file is opened with w, it is emptied: whatever was there before is lost.

Example

	fp= fopen("my_file","rw");

This says open a file called my_file which can be read (r) or written (w). If there is any error in trying to open the file, such as naming a file which is not available to you, then fopen returns the value NULL (which is conveniently defined for you in stdio.h) It is therefore essential to check this before trying to use the file:

	fp= fopen("my_file","rw");

	if (fp == NULL)
		{
		printf("my_file not available\\ n");
		exit(1);
		}

[Note that it is conventional, though not a requirement, to exit with zero for a successful completion; otherwise for an error]

or, equivalently:

	if ( (fp= fopen("my_file","rw") ) == NULL)
		{
		printf("my_file not available\\ n");
		exit(1);		/* quit the program */
		}

When you have finished with a file, you should call

	fclose(fp);



Next: File output Up: Input-Output Previous: Files


maspjw@
Tue Sep 27 15:29:34 BST 1994