> For the complete documentation index, see [llms.txt](https://docs.1l.lol/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://docs.1l.lol/complexity-debug/file-redirect.md).

# 文件重定向

### 文件重定向（freopen）

把标准输入输出重定向到文件，本地调试时不用手动输入：

```cpp
#include <cstdio>

int main() {
    freopen("in.txt", "r", stdin);    // 从 in.txt 读入
    freopen("out.txt", "w", stdout);  // 输出到 out.txt

    int a, b;
    cin >> a >> b;
    cout << a + b << endl;
    return 0;
}
```

* 第一个参数：文件名
* 第二个参数：`"r"` 读、`"w"` 写、`"a"` 追加
* 第三、四个参数：`stdin` / `stdout`

`freopen` 写在 `main` 开头，之前不要有输入输出。

### fstream 文件读写

```cpp
#include <fstream>
ifstream fin("in.txt");
ofstream fout("out.txt");

int a; fin >> a;
fout << a << endl;
fin.close(); fout.close();
```

### OJ 与本地调试的区别

* 本地调试：可加 freopen 直接读文件、看结果。
* 提交 OJ：**一般要去掉 freopen**，否则读不到题目数据（除非题目本身就要求文件输入输出）。
* 想两者兼顾可写成条件编译：

```cpp
#ifdef LOCAL
    freopen("in.txt", "r", stdin);
#endif
```

### 读取整行文件

```cpp
string line;
while (getline(fin, line)) cout << line << endl;
```


---

# Agent Instructions
This documentation is published with GitBook. GitBook is the documentation platform designed so that both humans and AI agents can read, navigate, and reason over technical content effectively. Learn more at gitbook.com.

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

Perform an HTTP GET request on the following URL with the `ask` and `goal` query parameters:

```
GET https://docs.1l.lol/complexity-debug/file-redirect.md?ask=<question>&goal=<user_goal>
```

`ask` is the immediate question: it should be specific, self-contained, and written in natural language.
`goal` is what the user is ultimately trying to achieve, the reason they need the answer. Sharing it helps GitBook give you a better, more relevant answer. A goal is most helpful when it describes the outcome the user wants rather than restating the question. For example, with `ask=how do I create an API token`, a goal like `automate deployments from our CI pipeline` lets GitBook tailor the answer to that use case.

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.
