在linux系統中將自己程式的日誌輸出到自己定義的檔案__linux

來源:互聯網
上載者:User
很簡單, 開啟檔案/寫入檔案. bash指令碼: echo "message" >> /path/to/yourlogfilec: 這個就不用說了吧, fopen("/path/to/yourlogfile", "a"); 然後調用fwrite如果希望printf/fprintf(stderr,等標準輸出/標準錯誤輸出直接輸出到日誌, 用dup2:#include <stdio.h>#include <unistd.h>int main(){    FILE *fp = fopen("log.txt", "a");    if(fp){        int no = fileno(fp);        dup2(no, 1);        dup2(no, 2);        printf("stdout log\n");        fprintf(stderr, "stderr log\n");        fclose(fp);    }    return 0;}
 
在C和C++中把標準輸出重新導向到指定檔案。   

2010-08-27 13:54:38|  分類: C++語言 |  標籤:標準輸出  檔案  memcpy  cout  endl  |字型大小 訂閱

問題內容:在C和C++中把標準輸出重新導向到指定檔案。

C++的實現 
#include <ios> 
#include <iostream> 
#include <fstream> 
//若使用包含.h檔案方式則編譯報錯 
using namespace std; 
int main() 

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

    return 0;

C實現1

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

 

C實現2::
#include<iostream>

#include<fstream>

using namespace std;

 

int main()

{

    freopen("intput.txt","r",stdin);

    freopen("output.txt","w",stdout);

    double a;

    cin>>a;

    cout<<"Jackie"<<endl;

    return 0;

}

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.