[C/C++标准库]_[使用freopen重定向标准输出]

2014-11-24 10:15:38 · 作者: · 浏览: 0


freopen


场景:

1.比如控制台打打印太长了,需要记录到文件上分析。

2.或者是做一些简单的日志工作就可以用到freopen。


代码:

#include 
  
   
#include 
   
     #include 
    
      #include 
     
       #include 
      
        #include 
       
         #include 
        
          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 screen
hello