[C/C++标准库]_[初级]_[使用freopen重定向标准输出]
来源:互联网 发布:查找算法 编辑:程序博客网 时间:2024/05/22 04:51
freopen
场景:
1.比如控制台打打印太长了,需要记录到文件上分析。
2.或者是做一些简单的日志工作就可以用到freopen。
代码:
#include <stdlib.h>#include <stdio.h>#include <string.h>#include <string>#include <iostream>#include <io.h>#include <assert.h>using namespace std;char *GetFileDirectory(const char *filename) { char *ret = NULL; char dir[1024]; char *cur; if (filename == NULL) return(NULL); #if defined(WIN32) && !defined(__CYGWIN__) # define IS_SEP(ch) ((ch=='/')||(ch=='\\')) #else # define IS_SEP(ch) (ch=='/') #endif strncpy(dir, filename, 1023); dir[1023] = 0; cur = &dir[strlen(dir)]; while (cur > dir) { if (IS_SEP(*cur)) break; cur --; } if (IS_SEP(*cur)) { if (cur == dir) { //1.根目录 dir[1] = 0; } else { *cur = 0; } ret = strdup(dir); } else { //1.如果是相对路径,获取当前目录 //io.h if (getcwd(dir, 1024) != NULL) { dir[1023] = 0; ret = strdup(dir); } } return ret; #undef IS_SEP } int main(int argc,char*argv[]){printf("file is %s\n",argv[0]);char* dir = GetFileDirectory(argv[0]);printf("dir is %s\n",dir);string dirs(dir);free(dir);dirs.append("/").append("log.txt");FILE* file = freopen(dirs.c_str(),"w",stdout); assert(file == stdout); printf("I am write into log.txt,not print to screen\n"); cout << "hello" << endl; fclose(stdout);string openFile("notepad.exe "); openFile.append(dirs.c_str()); system(openFile.c_str()); //注意:如果你想重置restore stdout,那么最好一开始就不要使用freopen重定向. //http://c-faq.com/stdio/undofreopen.html //如果非要重置就参考以下文章吧: //http://stackoverflow.com/questions/1908687/how-to-redirect-the-output-back-to-the-screen-after-freopenout-txt-a-stdo return 0;}
打开文件.log.txt:
I am write into log.txt,not print to screenhello
0 0
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]
- [C/C++标准库]_[初级]_[使用string stream]
- [C/C++标准库]_[初级]_[使用时间库]
- [C/C++标准库]_[初级]_[signal信号浅析]
- [C/C++标准库]_[初级]_[集合操作]
- [C/C++标准库]_[初级]_[分割字符串Split]
- [C/C++标准库]_[初级]_[unary_function 和 binary_function]
- [C/C++标准库]_[初级]_[unary_function 和 binary_function]
- [C/C++标准库]_[初级]_[不使用正则替换和删除字符串]
- [C/C++标准库]_[初级]_[使用auto_ptr智能指针]
- [C/C++标准库]_[初级]_[std::map的使用细节]
- [C/C++标准库]_[初级]_[函数对象functor的使用]
- [C/C++标准库]_[初级]_[优先队列priority_queue的使用]
- [C/C++标准库]_[初级]_[使用std::sort排序各种类型数据]
- [C/C++标准库]_[初级]_[使用模板删除字符串前后空格((w)string space)]
- [C/C++标准库]_[初级]_[使用fstream合并文本文件]
- [C/C++标准库]_[初级]_[使用正则表达式过滤Windows文件名中的非法字符]
- C标准重定向
- Sending 'ViewController' to Parameter of Incompatible Type 'id<xxxDelegate>'
- ORACLE 10g 安装教程[图文]
- 怎么样让人记住你的品牌
- sscanf函数用法详解
- 相对路径和绝对路径
- [C/C++标准库]_[初级]_[使用freopen重定向标准输出]
- 是男人就下100层【第一层】——高仿微信界面(7)
- quartz在集群环境下的解决方案
- 编码器设计
- ngx_event_pipe_read_upstream分析
- 点击小游戏来练习二位数组和动态生成winform 按钮
- uboot分析
- 第一次学c语言
- NYOJ 623 A*B Problem II