[英]ifstream: how to tell if specified file doesn't exist
我想打開一個文件進行閱讀。 但是,在這個程序的上下文中,如果文件不存在也沒關系,我繼續前進。 我希望能夠確定錯誤何時是“找不到文件”以及何時錯誤。 否則意味着我需要退出並出錯。
我沒有看到使用fstream
執行此操作的明顯方法。
我可以使用 C 的open()
和perror()
來做到這一點。 我假設也有一種fstream
方法可以做到這一點。
編輯:我已被告知這不一定表示文件不存在,因為它也可能因訪問權限或其他問題而被標記。
我知道我回答這個問題很晚,但我想無論如何我都會為任何瀏覽的人發表評論。 您可以使用 ifstream 的失敗指示器來判斷文件是否存在。
ifstream myFile("filename.txt");
if(myFile.fail()){
//File does not exist code here
}
//otherwise, file exists
我認為您無法知道“文件不存在”。 您可以使用 is_open() 進行通用檢查:
ofstream file(....);
if(!file.is_open())
{
// error! maybe the file doesn't exist.
}
如果您使用的是boost
,則可以使用boost::filesystem
:
#include <boost/filesystem.hpp>
int main()
{
boost::filesystem::path myfile("test.dat");
if( !boost::filesystem::exists(myfile) )
{
// what do you want to do if the file doesn't exist
}
}
由於打開文件的結果是特定於操作系統的,我認為標准 C++ 沒有任何方法來區分各種類型的錯誤。 該文件要么打開,要么不打開。
您可以嘗試打開文件進行讀取,如果它沒有打開( ifstream::is_open()
返回false
),您就知道它不存在或發生了其他一些錯誤。 再說一次,如果您之后嘗試打開它進行寫作並且失敗了,那可能屬於“其他”類別。
來自http://www.cplusplus.com/forum/general/1796/的簡單方法
ifstream ifile(filename);
if (ifile) {
// The file exists, and is open for input
}
您可以使用 stat,它應該可以跨平台移植並且在標准 C 庫中:
#include <sys/stat.h>
bool FileExists(string filename) {
struct stat fileInfo;
return stat(filename.c_str(), &fileInfo) == 0;
}
如果 stat 返回 0,則文件(或目錄)存在,否則不存在。 我假設您必須對文件路徑中的所有目錄具有訪問權限。 我還沒有測試可移植性,但這個頁面表明它不應該是一個問題。
更好的方法:
std::ifstream stream;
stream.exceptions(std::ifstream::failbit | std::ifstream::badbit);
stream.open(fileName, std::ios::binary);
對於 C++17,您可以使用std::filesystem::exists
。
函數std::fstream::good()
由於多種原因返回false
,包括文件不存在時。 還不夠嗎?
std::fstream
從std::ios
繼承此函數。
無需創建 ifstream 對象的直接方式。
if (!std::ifstream(filename))
{
// error! file doesn't exist.
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.