# 文件及目录处理

## 文件读取/写入操作

**打开函数:**

* fopen()

用来打开一个文件，打开时需要指定打开模式

打开模式r/r+、w/w+、a/a+、x/x+、b、t

**写入函数：**  <br>

* fwrite()
* fput()

**读取函数**  <br>

* fread()
* fgets()-获取一行
* fgetc()-获取一个字符

**关闭文件函数**  <br>

* fclose()

**不需要fopen打开的函数**  <br>

* file\_get\_contents()
* file\_put\_contents()

**其他读取函数**  <br>

* file()
* readfile()

**访问远程文件**  <br>

开启allow\_url\_fopen,HTTP协议连接只能使用只读，FTP协议可以使用只读或者只写

只要这样才能通过fopen()和file\_get\_contens()来进行远程读取

## 目录操作函数：

* 名称相关：basename(),dirname(),pathinfo()
* 目录读取：opendir()、readdir()、closedir()、rewinddir()
* 目录删除：rmdir() - 目录为空才能进行删除
* 目录创建:mkdir()
* 文件大小：filesize()
* 目录大小：disk\_free\_space() - 磁盘剩余空间、disk\_total\_space()
* 文件类型：filetype()-常见文件或目录
* 重命名文件或目录：rename()
* 文件截取ftruncate()
* 文件属性：file\_exists()、is\_readable()、is\_writable()、is\_executable()、filectime()、fileatime()、filemtime()

## 示例：

不断在文件hello.txt头部写入一行"hello world" 字符串，要求代码完整

```php
<?php

// 打开文件
//
// 将文件的内容读取出来，在开头加入Hello World
//
// 将拼接好的字符串写回到文件当中
//
// Hello abcefg
//
$file = './hello.txt';

$handle = fopen($file, 'r');

$content = fread($handle, filesize($file));

$content = 'Hello World'. $content;

fclose($handle);

$handle = fopen($file, 'w');

fwrite($handle, $content);

fclose($handle);
```

循环遍历目录

```php
<?php

$dir = './test';

// 打开目录
// 读取目录当中的文件
// 如果文件类型是目录，继续打开目录
// 读取子目录的文件
// 如果文件类型是文件，输出文件名称
// 关闭目录
//

function loopDir($dir)
{
    $handle = opendir($dir);

    while(false!==($file = readdir($handle)))
    {
        if ($file != '.' && $file != '..')
        {
            echo $file. "\n";
            if (filetype($dir. '/'. $file) == 'dir')
            {
                loopDir($dir. '/'. $file);
            }
        }
    }
}

loopDir($dir);
```


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://phper.shujuwajue.com/ji-chu/wen-jian-ji-mu-lu-chu-li.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
