一.freopen的使用(C/C++)
函数原型:FILE *freopen( const char *path, const char*mode, FILE *stream );
头文件: stdio.h
参数:
path: 文件名,用于存储输入输出的自定义文件名。
mode: 文件打开的模式。和fopen中的模式(如r-只读, w-写)相同。
stream: 一个文件,通常使用标准流文件。
返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。一般不使用。
功能:实现重定向,把预定义的标准流文件定向到由path指定的文件中。标准流文件具体是指stdin、stdout和stderr。其中stdin是标准输入流,默认为键盘;stdout是标准输出流,默认为屏幕;stderr是标准错误流,一般把屏幕设为默认。
例:
freopen("data.in", "r", stdin); //重定向标准输入为data.in文件
freopen("data.out", "w", stdout); //重定向标准输出为data.out文件
// 程序功能是统计输入的序列串中的最大值、最小值和序列串的平均值
#define LOCAL
#include <stdio.h>
// #include <iostream>
#define INF 1000000000
// using namespace std;
int main (void) {
#ifdef LOCAL
freopen ("data.in", "r", stdin);
freopen ("data.out", "w", stdout);
#endif
int x, n = 0, min = INF, max = -INF, s = 0;
while (scanf ("%d", &x) == 1) {
// while (cin >> x) {
s += x;
if (x < min) min = x;
if (x > max) max = x;
//printf ("x = %d, min = %d, max = %d\n", x, min, max);
++n;
}
printf ("%d %d %.3f\n", min, max, (double)s/n);
// cout << min << " " << max << " " << (double)s / n << endl;
return 0;
}
二.文件流使用(C)
fopen函数
函数原型:FILE * fopen(const char * path, const char * mode);
头文件: stdio.h
参数:
path: 文件名。
mode: 文件打开的模式。
返回值:成功,则返回一个path所指定文件的指针;失败,返回NULL。
// 程序功能是统计输入的序列串中的最大值、最小值和序列串的平均值
#include <stdio.h>
#define INF 1000000000
int main (void) {
FILE *fin, *fout;
fin = fopen ("data.in", "rb");
fout = fopen ("data.out", "wb");
int x, n = 0, min = INF, max = -INF, s = 0;
while (fscanf (fin, "%d", &x) == 1) {
s += x;
if (x < min) min = x;
if (x > max) max = x;
//printf ("x = %d, min = %d, max = %d\n", x, min, max);
++n;
}
fprintf (fout, "%d %d %.3f\n", min, max, (double)s/n);
fclose (fin);
fclose (fout);
return 0;
}
三.C++中文件流的使用
在C++中文件和string都可以转换为对应的输入输出流,由此可以简单对文件和string对象进行操作。具体的操作为:
1. 创建对应的流对象(文件流、String流,如:ifstream,ofstream,istringstream,ostringstream等)
2. 用对应的文件名(或string)初始化该流对象
经过上面两步,就可以很简单的对对应的流对象进行操作,跟标准输入输出流的操作方式一致(与cin、cout的使用方式一致)
#include <iostream>
#include <fstream>
#define INF 1000000000
using namespace std;
int main (void) {
ifstream fin("data.in");
ofstream fout ("data.out");
int x, n = 0, min = INF, max = -INF, s = 0;
while (fin >> x) {
s += x;
if (x < min) min = x;
if (x > max) max = x;
//printf ("x = %d, min = %d, max = %d\n", x, min, max);
++n;
}
fout << min << " " << max << " " << (double)s/n;
fout.close ();
fin.close ();
return 0;
}
类继承图: