您的位置:首页 > 运维架构

文件重定向函数freopen

2016-01-18 19:43 399 查看
头文件:stdio.h
FILE *freopen( const char *filename, const char *mode, FILE *stream );
参数说明:
filename:需要重定向到的文件名或文件路径。
mode:代表文件访问权限的字符串。例如,"r"表示“只读访问”、"w"表示“只写访问”、"a"表示“追加写入”。
stream:需要被重定向的文件流。
返回值:如果成功,则返回该指向该输出流的文件指针,否则返回为NULL。

下面举一个例子:假设E盘下面有两个文本文档in.txt和out.txt,其中in.txt中第一行是一个数字n,表示接下有n行字符串,out.txt是一个空文档,现在想要将in.txt中的内容全部复制到out.txt中,当然可以通过fopen,getc,putc等函数实现,但这里使用文件重定向,将in.txt重定向为stdin,将out.txt重定向为stdout,这样stdin和stdout中的函数本来应该是从屏幕上读取和输出数据的,就变成了从in.txt中读取数据,写入到out.txt中了。
程序如下:

#include<iostream>
#include<stdio.h>
using namespace std;
int main()
{
const char * in ="E:\\in.txt";
const char * out="E:\\out.txt";
if(freopen(in,"r",stdin)==NULL)
{
cout<<"in.txt 打开失败"<<endl;
return 0;
}
if(freopen(out,"w",stdout)==NULL)
{
cout<<"out.txt 打开失败"<<endl;
return 0;
}
int n;
cin>>n;
cin.get();
cout<<n;
char str[50];
while(n)
{
cin.getline(str,8);
cout<<str<<endl;
n--;
}
return 0;
}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: