文件重定向

文件重定向指的是将标准输入输出,例如 cin 和 cout,从控制台重定向到文件中。
常见的文件重定向方法有:freopen 函数和 fstream 对象。

一、freopen 函数

用来打开一个文件流,并将其与标准输入 stdin、标准输出 stdout 关联,需包含 <cstdio> 头文件。

freopen("读入文件", "r", stdin);
freopen("输出文件", "w", stdout);

fclose(stdin);
fclose(stdout);

二、fstream 对象

用来创建文件流对象,如 ifstream、ofstream,然后使用这些对象进行输入输出,需包含 <fstream> 头文件。

  • ifstream:读取文件,Input File Stream
  • ofstream:写入文件,Output File Stream
  • fstream:读写文件,File Stream
#include <iostream>
#include <fstream>

int main() {
    // ========== 方式一:在构造函数中直接打开文件 ==========
    std::ifstream inFile1("test.in");
    std::ofstream outFile1("test.out");

    outFile1 << "Welcome to GESP!" << std::endl;

    inFile1.close();
    outFile1.close();

    // ========== 方式二:先创建对象,再用 open() 函数打开文件 ==========
    std::ifstream inFile2;
    std::ofstream outFile2;

    // 以二进制读模式打开文件,ios::in 是默认模式,可省略
    inFile2.open("test.in", std::ios::in | std::ios::binary);

    // 以二进制写模式打开文件,ios::out 是默认模式,可省略
    outFile2.open("test.out", std::ios::out | std::ios::binary);

    outFile2 << "Welcome to GESP!" << std::endl;

    inFile2.close();
    outFile2.close();

    return 0;
}