博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
C library function - freopen()
阅读量:4337 次
发布时间:2019-06-07

本文共 2236 字,大约阅读时间需要 7 分钟。

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.
  • stream − This is the pointer to a FILE object that identifies the stream to be re-opened.

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 
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 
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); }

转载于:https://www.cnblogs.com/zhonghuasong/p/5008322.html

你可能感兴趣的文章
OO第一次总结博客
查看>>
day7
查看>>
iphone移动端踩坑
查看>>
vs无法加载项目
查看>>
Beanutils基本用法
查看>>
玉伯的一道课后题题解(关于 IEEE 754 双精度浮点型精度损失)
查看>>
《BI那点儿事》数据流转换——百分比抽样、行抽样
查看>>
哈希(1) hash的基本知识回顾
查看>>
Leetcode 6——ZigZag Conversion
查看>>
dockerfile_nginx+PHP+mongo数据库_完美搭建
查看>>
Http协议的学习
查看>>
【转】轻松记住大端小端的含义(附对大端和小端的解释)
查看>>
设计模式那点事读书笔记(3)----建造者模式
查看>>
ActiveMQ学习笔记(1)----初识ActiveMQ
查看>>
Java与算法之(2) - 快速排序
查看>>
Windows之IOCP
查看>>
机器学习降维之主成分分析
查看>>
WebSocket & websockets
查看>>
openssl 升级
查看>>
ASP.NET MVC:通过 FileResult 向 浏览器 发送文件
查看>>