freopen-C/C++方便的文件输入输出
2016-04-23 12:14
627 查看
#include <stdio.h> // 实际使用中发现freopen也包含在iostream中,C++代码#include <iostream>即可。 int main() { freopen("sample.in", "r", stdin); freopen("sample.out", "w", stdout); /* 同控制台输入输出 */ fclose(stdin); fclose(stdout); return 0; }
函数名:freopen
声明: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是标准错误流,一般把屏幕设为默认。
下面为两个a+b测试程序
C语法
#include<stdio.h> int main() { freopen("input.txt", "r", stdin); freopen("out.txt","w",stdout); int a, b; scanf("%d %d",&a,&b); printf("%d\n",a+b); fclose(stdin); fclose(stdout); return 0; }
C++语法
#include<iostream> #include<stdio.h> using namespace std; int main() { freopen("input.txt", "r", stdin); freopen("out.txt","w",stdout); int a, b; cin>>a>>b; cout<<a+b; return 0; }
freopen("input.txt","r",stdin)的作用就是把标准输入流stdin重定向到input.txt文件中,这 样在用scanf或是用cin输入时便不会从标准输入流读取数据,而是从input.txt文件中获取输入。只要把输入数据事先粘贴到input.txt,调试时就方 便多了。
类似的,freopen("out.txt","w",stdout)的作用就是把stdout重定向到out.txt文件中,这样输出结果需要打开out.txt文件查看。
相关文章推荐
- C/C++学习笔记(2)--函数模板template<typename T>,类模板详解(1)
- [C++]Stack with Template
- C++ 效率
- c语言.野指针
- C++ string 常用函数/方法
- JAVA使用JNI调用C++动态链接库
- S3C2440之UART0
- VC++深入详解第一章代码
- Notepad++插件:文件目录,自动补全,显示类,命令行
- 用实例讲解栈和队列(C++)
- c语言:输入一行字符,统计其中的单词个数,单词之间用空格分开
- Leetcode 9. Palindrome Number
- C++中vector内存泄露问题
- C语言中的隐式转换
- C语言中不同类型的指针互相转换的注意点
- c++实现二叉树(递归)
- c++ 读书目录
- C语言基础及数据类型
- c语言中,scanf里面要是数组要不要加&?
- C++ 复杂链表的复制