[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]


close

Close an open file.

Compatibility:

This function is compatible with the following targets:

ANSI

BeOS

EMB/RTOS

Mac OS

Palm OS

Win32


Prototype:
#include <unistd.h>
int close(int fildes);
Parameters:

Parameters for this facility are:

fildes  
int  
The file descriptor  

Remarks:

The close() function closes the file specified by the argument. This argument is the value returned by open().Example of usage is given in "Example of close() usage."

Return:

If successful, close() returns zero. If unsuccessful, close() returns negative one and sets errno.

See Also:

"open"

"fclose"

"errno"

Example of close() usage.:
#include <stdio.h>
#include <stdlib.h>
#include <fcntl.h>
#include <string.h>
#include <unistd.h>


#define SIZE FILENAME_MAX
#define MAX 1024

char fname[SIZE] = "DonQ.txt";


int main(void)
{ 
	int fdes;
	char temp[MAX];
	char *Don = "In a certain corner of la Mancha, the name of\n\
which I do not choose to remember,...";
	char *Quixote = "there lived\none of those country\
 gentlemen, who adorn their\nhalls with rusty lance\
 and worm-eaten targets.";

	/* NULL terminate temp array for printf */
	memset(temp, '\0', MAX);  

	/* open a file */
	if((fdes = open(fname, O_RDWR | O_CREAT ))== -1)
	{
		perror("Error ");
		printf("Can not open %s", fname);
		exit( EXIT_FAILURE);
	}
		
	/* write to a file  */
	if( write(fdes, Don, strlen(Don)) == -1)
	{
		printf("%s Write Error\n", fname);
		exit( EXIT_FAILURE );
	}  	 

	/*	move back to over write ... characters */ 
	if( lseek( fdes, -3L, SEEK_CUR ) == -1L)
	{
		printf("Seek Error");
		exit( EXIT_FAILURE );
	}  
	
	/* write to a file  */
	if( write(fdes, Quixote, strlen(Quixote)) == -1)
	{
		printf("Write Error");
		exit( EXIT_FAILURE );
	}  	 
		
	/* move to beginning of file for read */
	if( lseek( fdes, 0L, SEEK_SET ) == -1L)
	{
		printf("Seek Error");
		exit( EXIT_FAILURE );
	}  
	
	/* read the file  */
	if( read( fdes, temp, MAX ) == 0)
	{
		printf("Read Error");
		exit( EXIT_FAILURE);
	}
	
	/* close the file */ 
	if(close(fdes))
	{
		printf("File Closing Error");
		exit( EXIT_FAILURE );
	}

	 puts(temp);  

	return 0;
}

Result
In a certain corner of la Mancha, the name of
which I do not choose to remember,there lived
one of those country gentlemen, who adorn their
halls with rusty lance  and worm-eaten targets.


[ First ]  [ Previous ]  [ Next ]  [ Last ]  [ Manuals ]

Visit the Metrowerks website at: http://www.metrowerks.com
For assistance contact Metrowerks Technical Support at: cw_support@metrowerks.com
Copyright © 2000, Metrowerks Corp. All rights reserved.

Last updated: August 16, 2000