본문 바로가기
C 언어

fopen

by SpeeDr00t 2016. 7. 9.
반응형

FILE *

fopen(const char *file, const char *mode)

#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <limits.h>
#include <stdio.h>
#include <errno.h>
#include <unistd.h>
#include "local.h"

FILE *
fopen(const char *file, const char *mode)
{
	FILE *fp;
	int f;
	int flags, oflags;

	if ((flags = __sflags(mode, &oflags)) == 0)
		return (NULL);
	if ((fp = __sfp()) == NULL)
		return (NULL);
	if ((f = open(file, oflags, DEFFILEMODE)) < 0) {
		fp->_flags = 0;			/* release */
		return (NULL);
	}

	/* _file is only a short */
	if (f > SHRT_MAX) {
		fp->_flags = 0;			/* release */
		close(f);
		errno = EMFILE;
		return (NULL);
	}

	fp->_file = f;
	fp->_flags = flags;
	fp->_cookie = fp;
	fp->_read = __sread;
	fp->_write = __swrite;
	fp->_seek = __sseek;
	fp->_close = __sclose;

	/*
	 * When opening in append mode, even though we use O_APPEND,
	 * we need to seek to the end so that ftell() gets the right
	 * answer.  If the user then alters the seek pointer, or
	 * the file extends, this will fail, but there is not much
	 * we can do about this.  (We could set __SAPP and check in
	 * fseek and ftell.)
	 */
	if (oflags & O_APPEND)
		(void) __sseek((void *)fp, (fpos_t)0, SEEK_END);
	return (fp);
}
반응형

'C 언어' 카테고리의 다른 글

fseek  (0) 2016.07.09
_fwalk  (0) 2016.07.09
fgetc  (0) 2016.07.09
fgets  (0) 2016.07.09
fwrite  (0) 2016.07.09