# 基础

## 文本文件和二进制文件有什么不同？

* 文本文件是**基于字符编码**的文件
* 除了文本文件以外的文件称为二进制文件
* **二进制文件编码是变长的**，灵活利用率高
* 两者读写差别仅体现在**回车换行符**的处理上
* **文本文件是一种特殊的“二进制文件”**

## 文件的打开方式

```php
$handle = fopen( 'test.txt', 'r' );
```

![](/files/-LfnTHeYMuRR0HElplDd)

> 文件的打开方式的特殊标记
>
> 1、标记（‘t’）可以将 \n 转换为 \r\n （windows下）
>
> ```php
> $handle = fopen('test.txt', 'wt');
> ```
>
> 2、标记 (‘b’) 来强制使用二进制模式
>
> ```php
> $handle = fopen('test.txt', 'rb');
> ```

示例:

`r`**只读方式打开**

```php
$handle = fopen("import.txt", "r");
echo fputs($handle ,'是否能写入？');
```

输出0,无法写入

`r+`**读写方式打开**

```php
$handle = fopen("import.txt", "r+");
echo fputs($handle ,'是否能写入？');
```

注意:指针指向文件开头,所以如果文件中已经存在数据,则添加的数据会在文件开头.

**w 写入方式打开**

```php
$handle = fopen("import.txt", "w");
$content=fgets($handle);
var_dump($content);
```

因为只能写入,所以读取不成功,返回fasle

**注意:原有的文件数据会被清空**

**w+读写方式打开**

```php
$handle = fopen("import.txt", "w+");
fputs($handle, '我写写！');
rewind($handle);  //倒回文件指针的位置
$content=fgets($handle);
var_dump($content);
```

**注意:原有的文件数据会被清空**

**x写方式打开**

```php
//文件不能先存在，否则 fopen() 调用失败并返回 FALSE，并生成一条 E_WARNING 级别的错误信息
$handle = fopen("write.txt", "x");
var_dump($handle);
```

**c写入方式打开**

```php
<?php
//覆盖模式，不会清空已有的文件。
$handle = fopen("write.txt", "c");
fputs($handle, "1");
fseek($handle, 3);
fputs($handle, '2');
```

## 与文件操作相关的封装协议

```php
fopen('php//stdout', 'w');
```

或者

```
file:// - 访问本地文件系统
http::// - 访问HTTP(s) 网址.
ftp:// 访问FTP(s) URLs
php:// - 访问各个输入/ 输出流(I/O streams)
zlib:// - 压缩流 :http://php.net/manual/zh/wrappers.compression.php
```

[更多请看](http://php.net/manual/zh/wrappers.php)

**命令行输出流**

```php
$fp = fopen('php://stdout', 'w');
fputs($fp, 'hello world!');
```

等同于

```php
fputs(STDOUT, 'hello world!');
```

相当于echo

**命令行输入流**

```php
$fp = fopen('php://stdin', 'r');
echo fgets($fp);
```

上面两句等同于

```php
echo fgets(STDIN);
```

集合体

```php
fputs(STDOUT, strtoupper(fgets(STDIN)));
```

获取输入, 并输出


---

# 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/phpwen-jian-bian-cheng/ji-chu.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.
