C library function - freopen()
2015-11-30 20:41
323 查看
Description
The C library function FILE *freopen(const char *filename, const char *mode, FILE *stream) associates a new filename with the given open stream and at the same time closes the old file in the stream.Declaration
Following is the declaration for freopen() function.FILE *freopen(const char *filename, const char *mode, FILE *stream)
Parameters
filename − This is the C string containing the name of the file to be opened.mode − This is the C string containing a file access mode. It includes −
mode | Description |
---|---|
"r" | Opens a file for reading. The file must exist. |
"w" | Creates an empty file for writing. If a file with the same name already exists then its content is erased and the file is considered as a new empty file. |
"a" | Appends to a file. Writing operations appends data at the end of the file. The file is created if it does not exist. |
"r+" | Opens a file to update both reading and writing. The file must exist. |
"w+" | Creates an empty file for both reading and writing. |
"a+" | Opens a file for reading and appending. |
Return Value
If the file was re-opened successfully, the function returns a pointer to an object identifying the stream or else, null pointer is returned.Example
The following example shows the usage of freopen() function.#include <stdio.h> int main () { FILE *fp; printf("This text is redirected to stdout\n"); fp = freopen("file.txt", "w+", stdout); printf("This text is redirected to file.txt\n"); fclose(fp); return(0); }
Let us compile and run the above program that will send the following line at STDOUT because initially we did not open stdout −
This text is redirected to stdout
After a call to freopen(), it associates STDOUT to file file.txt, so whatever we write at STDOUT that goes inside file.txt. So, the file file.txt will have the following content.
This text is redirected to file.txt
Now let's see the content of the above file using the following program −
#include <stdio.h> int main () { FILE *fp; int c; fp = fopen("file.txt","r"); while(1) { c = fgetc(fp); if( feof(fp) ) { break ; } printf("%c", c); } fclose(fp); return(0); }
相关文章推荐
- tomcat热启动
- Docker:使用pipework配置docker网络
- Apache Mesos 官方文档 V1.0
- linux_根据关键词_路径下递归查找code
- 动态代理实现AOP【转】
- MVC随笔之基础数据维护(MVC4+Boostrap)
- Linux 注销 登录 重启
- Device eth0 does not seem to be present, delaying initialization(解决克隆CentOS6.3虚拟机后网卡设备无法启动问题)
- FIFO,LRU,OPT置换算法
- arm-linux内核编译过程小结
- OpenCV访问图像数据并设定灰度值
- LINUX集群技术构建ANSYS分布式高性能计算平台
- hdu1053 Entropy
- 各种软件架构风格
- Linux第三次实验报告
- NGINX部署项目后浏览器选项卡icon图标不显示
- 【c#】—架构函数&&析构函数
- shell笔记-local、export用法 、declare、set
- linux下自动挂载samba目录
- Properties--配置文件的加载