4. 程序设计比赛-常用技巧

无穷大

0x3f3f3f3f

freopen()

头文件

stdio.h 或者 cstdio (如果是C11,iostream似乎已经包含了,若是C98需要加上 #include <cstdio>)

声明

  
1
FILE *freopen(const char *filename, const char *mode, FILE *stream)

参数

  - filename -- 文件名,用于存储输入输出的自定义文件名。
  - mode -- 文件打开的模式。和fopen中的模式(如: `r` -- "只读访问"、`w` -- "只写访问"、`a` -- "追加写入")相同。
  - stream -- 一个文件,通常使用标准流文件。如:`stdin` -- 标准输入、`stdout` -- 标准输出、`stderr`(一般不用) -- 标准错误
  1. 模式
  2. 功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。
  3. 实例
    1. stdout 到一个文本文件的重定向,即:把输出到屏幕的文本输出到一个文本文件中

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      17
      #include <iostream>
      #include <cstdio>
      using namespace std;

      int main()
      {
      if(freopen("./output.txt","r",stdout)==NULL)
      fprintf(stderr,"error redirecting stdout\n");

      for(int i=0;i<10;i++)
      printf("%3d",i);

      printf("\n");
      fclose(stdout);

      return 0;
      }
    2. 从文件 in.txt 中读入数据,打印到屏幕上

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      #include <iostream>
      #include <cstdio>
      using namespace std;

      int main()
      {
      int a, b;
      freopen("./in.txt", "r", stdin);
      // freopen("out.txt", "a", stdout);
      while (cin >> a >> b)
      cout << a + b << endl;
      fclose(stdin);
      fclose(stdout);

      return 0;
      }
    3. 从文件 in.txt 中读入数据,计算加和输出到 out.txt

      1
      2
      3
      4
      5
      6
      7
      8
      9
      10
      11
      12
      13
      14
      15
      16
      #include <iostream>
      #include <cstdio>
      using namespace std;

      int main()
      {
      int a, b;
      freopen("./in.txt", "r", stdin);
      freopen("out.txt", "a", stdout);
      while (cin >> a >> b)
      cout << a + b << endl;
      fclose(stdin);
      fclose(stdout);

      return 0;
      }
> Note: 一般常用的是 `6.2`,因为有些比赛的命令行不能粘贴,一个个的打又太麻烦了,这样就会方便很多

导入全部头文件

1
#include <bits/stdc++.h>