文件重定向函数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中了。
程序如下:
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; }
相关文章推荐
- nginx结合tomcat一起使用
- linux下时区的一些认识
- Linux进程间通信——使用消息队列
- Linux Screen 超简单用法
- Tomcat限制文件上传大小(转)
- hadoop常用算法简单实例
- LINUX nfs服务
- JSLinux--A web linux base on Javascript and QEMU
- qt在linux打开串口写数据
- 关于tomcat环境下上传大文件遇到的问题及解决办法
- centos6.7 搭建jenkins
- R语言包在linux上的安装、卸载
- Nginx
- ubutnu引导丢失,恢复引导办法
- Linux学习之nl命令
- ubuntu中apache的配置
- ubuntu中安装和卸载apache2、php、mysql
- dede如何添加搜索功能, 让网站支持搜索
- QDebug &operator<<出错(根据QString来找,是不得要领的,而是应该根据QString所在的对象来思考)
- 一张图看尽 Linux 内核运行原理