2011-04-12 110 views
5

可能重複:
C++ alternative to perror()相當於perror的C++流是什麼?

我無法找到等價流至perror。有這樣的事嗎?我喜歡這樣的事實,我可以打電話:

perror("Error"); 

而且它會在什麼errno是填補。我可以用流做這個嗎?

+0

@Erik:是的......我之前看到的功能,我只是無法拿出一遍。謝謝! – Andrew 2011-04-12 20:04:47

回答

14

要打印的錯誤消息:

str << strerror(errno); 

如果你談論的流錯誤狀態 - 不,你不能得到一個自動有意義的錯誤消息爲。

4

由於perror寫入stderr,在C++中的任何等價物必須完全相同。也就是說,將strerror(errno)寫入流是不夠的。流本身應該(我會說必須)是一個流標準錯誤

下面的代碼片段/僞代碼應該給你一個想法:

// depending on your compiler, this is all you need to include 
#include <iostream> 
#include <string.h> 
#include <errno.h> 

... somewhere in your code... 

std::cerr << "Error: " << strerror(errno) << std::endl;