PHP会在file();
函数后自动关闭文件,还是需要fclose();
或类似文件?
答案 0 :(得分:1)
PHP会在文件()之后自动关闭文件吗?功能,还是需要fclose();或者类似的?
不,file()
不需要fclose()
来电。你可以看到,在函数的源代码中,它们都很好地结束了,所以你不必调用fclose()
或做类似的事情,你可以简单地调用file()
。 / p>
/* {{{ proto array file(string filename [, int flags[, resource context]])
Read entire file into an array */
PHP_FUNCTION(file)
{
char *filename;
size_t filename_len;
char *p, *s, *e;
register int i = 0;
char eol_marker = '\n';
zend_long flags = 0;
zend_bool use_include_path;
zend_bool include_new_line;
zend_bool skip_blank_lines;
php_stream *stream;
zval *zcontext = NULL;
php_stream_context *context = NULL;
zend_string *target_buf;
/* Parse arguments */
if (zend_parse_parameters(ZEND_NUM_ARGS(), "p|lr!", &filename, &filename_len, &flags, &zcontext) == FAILURE) {
return;
}
if (flags < 0 || flags > (PHP_FILE_USE_INCLUDE_PATH | PHP_FILE_IGNORE_NEW_LINES | PHP_FILE_SKIP_EMPTY_LINES | PHP_FILE_NO_DEFAULT_CONTEXT)) {
php_error_docref(NULL, E_WARNING, "'" ZEND_LONG_FMT "' flag is not supported", flags);
RETURN_FALSE;
}
use_include_path = flags & PHP_FILE_USE_INCLUDE_PATH;
include_new_line = !(flags & PHP_FILE_IGNORE_NEW_LINES);
skip_blank_lines = flags & PHP_FILE_SKIP_EMPTY_LINES;
context = php_stream_context_from_zval(zcontext, flags & PHP_FILE_NO_DEFAULT_CONTEXT);
stream = php_stream_open_wrapper_ex(filename, "rb", (use_include_path ? USE_PATH : 0) | REPORT_ERRORS, NULL, context);
if (!stream) {
RETURN_FALSE;
}
/* Initialize return array */
array_init(return_value);
if ((target_buf = php_stream_copy_to_mem(stream, PHP_STREAM_COPY_ALL, 0)) != NULL) {
s = target_buf->val;
e = target_buf->val + target_buf->len;
if (!(p = (char*)php_stream_locate_eol(stream, target_buf))) {
p = e;
goto parse_eol;
}
if (stream->flags & PHP_STREAM_FLAG_EOL_MAC) {
eol_marker = '\r';
}
/* for performance reasons the code is duplicated, so that the if (include_new_line)
* will not need to be done for every single line in the file. */
if (include_new_line) {
do {
p++;
parse_eol:
add_index_stringl(return_value, i++, s, p-s);
s = p;
} while ((p = memchr(p, eol_marker, (e-p))));
} else {
do {
int windows_eol = 0;
if (p != target_buf->val && eol_marker == '\n' && *(p - 1) == '\r') {
windows_eol++;
}
if (skip_blank_lines && !(p-s-windows_eol)) {
s = ++p;
continue;
}
add_index_stringl(return_value, i++, s, p-s-windows_eol);
s = ++p;
} while ((p = memchr(p, eol_marker, (e-p))));
}
/* handle any left overs of files without new lines */
if (s != e) {
p = e;
goto parse_eol;
}
}
if (target_buf) {
zend_string_free(target_buf);
}
php_stream_close(stream);
}
/* }}} */
从底部看到最后的第3行它结束了这个函数很好并且干净了:
php_stream_close(stream);