2010-09-08 31 views
1
#include <iostream> 
#include <fstream> 
using namespace std; 

void foo(){ 
    streambuf *psbuf; 
    ofstream filestr; 
    filestr.open ("test.txt"); 
    psbuf = filestr.rdbuf(); 
    cout.rdbuf(psbuf);  
} 

int main() { 
    foo(); 
    cout << "This is written to the file"; 
    return 0; 
} 

cout是否寫入給定文件?用C++重定向

如果沒有,有沒有辦法做到這一點,而不會將變量發送到foo,如new


更新

我不能使用,使用類或使用的解決方案全球化,所以PLZ可以將某些 給我使用了新的解決方案。還將主要傳遞給foo

streambuf *psbuf; 
ofstream filestr; 

應該正常工作嗎?

我想這樣做,但它不工作? 我將流傳遞給foo,所以它存在於main中,所以當foo完成時它不會結束。

void foo(streambuf *psbuf){ 

    ofstream filestr; 
    filestr.open ("test.txt"); 
    psbuf = filestr.rdbuf(); 
    cout.rdbuf(psbuf);  
} 

int main() { 
streambuf *psbuf 
    foo(psbuf); 
    cout << "This is written to the file"; 
    return 0; 
} 

回答

1

在我看來,你的代碼應該工作,但...你爲什麼不試試自己?你會看到,如果一切都寫在test.txt或不。

+0

在我看來,它沒有,但你的問題仍然是:-) – Johnsyweb 2010-09-08 11:50:01

+1

@johnsyweb哦對filestr有效被銷燬。我沒有仔細閱讀...... – log0 2010-09-08 11:55:26

4

我懷疑現在編譯並運行你的代碼,發現你得到了分段錯誤。

由於您在foo()內創建並打開了一個ofstream對象,因此在foo的末尾銷燬(並關閉)了此對象。當您嘗試寫入main()中的流時,您嘗試訪問不再存在的緩衝區。

一個解決方法是讓您的filestr對象成爲全局對象。有很多更好的!

編輯:這裏是一個更好的解決方案通過@MSalters的建議:

#include <iostream> 
#include <fstream> 

class scoped_cout_redirector 
{ 
public: 
    scoped_cout_redirector(const std::string& filename) 
     :backup_(std::cout.rdbuf()) 
     ,filestr_(filename.c_str()) 
     ,sbuf_(filestr_.rdbuf()) 
    { 
     std::cout.rdbuf(sbuf_); 
    } 

    ~scoped_cout_redirector() 
    { 
     std::cout.rdbuf(backup_); 
    } 

private: 
    scoped_cout_redirector(); 
    scoped_cout_redirector(const scoped_cout_redirector& copy); 
    scoped_cout_redirector& operator =(const scoped_cout_redirector& assign); 

    std::streambuf* backup_; 
    std::ofstream filestr_; 
    std::streambuf* sbuf_; 
}; 


int main() 
{ 
    { 
     scoped_cout_redirector file1("file1.txt"); 
     std::cout << "This is written to the first file." << std::endl; 
    } 


    std::cout << "This is written to stdout." << std::endl; 

    { 
     scoped_cout_redirector file2("file2.txt"); 
     std::cout << "This is written to the second file." << std::endl; 
    } 

    return 0; 
} 
+1

「有更好的」。的確,但是如果沒有指針,很難找到它們。這裏是一個:閱讀RAII。大部分來自函數foo的代碼應該被移動到構造函數中,並且匹配的析構函數應該執行清理操作(例如將cout恢復到舊狀態)。 – MSalters 2010-09-08 12:06:00

+0

確實。將代碼從http://www.cplusplus.com/reference/iostream/ios/rdbuf/提取到「foo()」時,@mati似乎故意省略了將'cout'恢復到其以前的狀態。 RAII似乎遠遠超出了問題的範圍。 – Johnsyweb 2010-09-08 12:10:12