2014-03-06 15 views
3

這會創建文件,但不會寫入任何內容。無法使用__gnu_cxx :: stdio_filebuf進行輸出

std::ofstream outstream; 
FILE * outfile; 

outfile = fopen("/usr7/cs/test_file.txt", "w"); 

__gnu_cxx::stdio_filebuf<char> filebuf(outfile, std::ios::out); 
outstream.std::ios::rdbuf(&filebuf); 

outstream << "some data"; 
outstream.close(); 
fclose(outfile); 

我知道有其他簡單的解決方案來實現輸出,但我需要使用非標準filebuf鎖定,同時編輯一個文件,以便其他進程無法打開該文件。 我不知道爲什麼這不起作用。

+0

您是否嘗試過實際打開'outstream'? – 0x499602D2

+0

我想你應該創建一個'std :: ostream'並從緩衝區構造它,就像'std :: ostream outstream(&filebuf)'一樣,所以你不必調用'open()'/'close )'沒有真正的原因。如果你這樣做,你也需要執行'outstream.std :: ios :: rdbuf(&filebuf);'。 – 0x499602D2

+0

對不起,不描述使用_gnu非標準filebuf的原因。我知道其他簡單的解決方案可以產生輸出,但我正在使用這種方法在編輯時鎖定文件;使其他進程無法打開文本文件。 – user3375257

回答

1

std::ostream已經有一個構造函數做正確的事:

#include <ext/stdio_filebuf.h> 
#include <iostream> 
#include <fcntl.h> 

int main() { 
    auto file = fopen("test.txt", "w"); 
    __gnu_cxx::stdio_filebuf<char> sourcebuf(file, std::ios::out); 
    std::ostream out(&sourcebuf); 
    out << "Writing to fd " << sourcebuf.fd() << std::endl; 
} 

記住stdio_filebuf不會關閉,當它被摧毀的FILE*,所以要記住,做你自己,如果你需要它。