在C和C++中把标准输出重定向到指定文件

来源:互联网 发布:蓝天windows一键重装 编辑:程序博客网 时间:2024/04/29 04:42

C++的实现 
#include<fstream>  

#include <iostream>

using namespace std;
int main()
{   
 ofstream logTest("foo.log");    
 streambuf *oldbuf = cout.rdbuf(logTest.rdbuf());   
  
 cout << "输出到标准输出,但实际输出到了foo.log文件中/n";    
 logTest << "输出到文件,虽然将cout重定向到了log,但不影响log本身的使用/n";   
  
  // 恢复流缓冲区    
  cout.rdbuf(oldbuf);

  cout << "输出到标准输出/n";  

  getchar();
}   


C的实现 
#include <ios> 
#include <iostream> 
#include <fstream> 
//若使用包含.h文件方式则编译报错 

using namespace std; 

void main() 

    ofstream ofs("e://a.txt"); 
    streambuf *osb = cout.rdbuf(ofs.rdbuf()); 
    cout << "to file" << endl; 
    cout.rdbuf(osb); 
    cout << "to term" << endl; 


啊,这样对于实现来说可能不是很妥,改成手动刷新缓冲才有应用价值 
#include <stdio.h> 
#include <string.h> 

void main() 

    FILE old_stdout; 
    FILE *fp = fopen("e://a.txt", "w"); 

    memcpy(&old_stdout, &_iob[1], sizeof(FILE)); 
    memcpy(&_iob[1], fp, sizeof(FILE)); 
     
    /*call any functions..*/ 
    printf("to file"); 
    /**/ 

    /*把缓冲刷新到文件*/ 
    fflush(stdout); 
    memcpy(&_iob[1], &old_stdout, sizeof(FILE)); 
    printf("to term"); 
    fclose(fp); 
}

原创粉丝点击