ACM中freopen的使用

2020-08-11 19:50:31

百度百科上的定義:

freopen是被包含於C標準庫標頭檔案<stdio.h>中的一個函數,用於重定向輸入輸出流。該函數可以在不改變程式碼原貌的情況下改變輸入輸出環境,但使用時應當保證流是可靠的。

用途一:

輸入重定向。當偵錯程式碼時,可以將測試數據存在 in.txt 檔案中,用freopen讀取

測試:

寫出下面 下麪的程式碼

#include <cstdio>
#include <iostream>
using namespace std;

int main(void)
{
	int a, b;
	// 輸入重定向,讀取 in.txt 中的數據 
	freopen("in.txt", "r", stdin);
	
	cin >> a >> b;
	cout << a + b << endl;
	
	// 關閉輸入流 
	fclose(stdin);
	
	return 0;
}

在當前程式碼的目錄下建立一個 in.txt,裏面的內容爲

1 2

執行程式碼,執行結果爲

3

用途二:

輸出重定向。將輸出數據儲存在 out.txt 檔案中

測試:

寫出如下的程式碼

#include <cstdio>
#include <iostream>
using namespace std;

int main(void)
{
	int a, b;
	// 輸入重定向,讀取 in.txt 中的數據 
	freopen("in.txt", "r", stdin);
	// 輸出重定向,將答案寫入 out.txt 中 
	freopen("out.txt", "w", stdout);
	
	cin >> a >> b;
	cout << a + b << endl;
	
	// 關閉輸入流 
	fclose(stdin);
	// 關閉輸出流 
	fclose(stdout);
	
	return 0;
}

在當前程式碼的目錄下建立一個 in.txt,裏面的內容爲

1 2

執行程式,發現當前目錄出現了一個 out.txt,裏面的內容爲

3

用途三:

多組輸入

測試:

#include <cstdio>
#include <iostream>
using namespace std;

int main(void)
{
	int a, b;
	// 輸入重定向,讀取 in.txt 中的數據 
	freopen("in.txt", "r", stdin);
	
	while (cin >> a >> b) {
		cout << a + b << endl;
	}
	
	// 關閉輸入流 
	fclose(stdin);
	
	return 0;
}

在當前程式碼的目錄下建立一個 in.txt,裏面的內容爲

1 1
2 2
3 3
4 4

執行程式碼,執行結果爲

2
4
6
8