CKTIS / C++
std::filesystem::exists: sprawdzanie rozpoznanego stanu ścieżki
std::filesystem::exists zwraca true, gdy stan ścieżki jest znany i nie oznacza file_type::not_found.
Wersja: C++23
Składnia
bool std::filesystem::exists(std::filesystem::file_status s) noexcept;
bool std::filesystem::exists(const std::filesystem::path& p);
bool std::filesystem::exists(
const std::filesystem::path& p, std::error_code& ec) noexcept;std::filesystem::exists(p) z <filesystem> pobiera status(p), więc domyślnie podąża za dowiązaniem symbolicznym, i testuje status_known(s) && s.type() != file_type::not_found. Istnieje też bezrzutowe przeciążenie dla gotowego file_status.
Przykład tworzy plik, sprawdza plik i brakującą ścieżkę wariantem z error_code, po czym drukuje 1 0 0: plik istnieje, brakujący nie istnieje, a zwykły brak nie pozostawił błędu.
false nie zawsze znaczy „na pewno nie istnieje”: brak uprawnień lub inny błąd może uniemożliwić ustalenie stanu. W wariancie z ec sprawdzaj jednocześnie wynik i ec; gdy stan jest znany, funkcja czyści ec. Wiszące dowiązanie daje false, bo status śledzi cel; do sprawdzania samego dowiązania użyj symlink_status i exists(file_status).
Przykłady
#include <filesystem>
#include <fstream>
#include <iostream>
int main() {
namespace fs = std::filesystem;
const fs::path root = fs::temp_directory_path() / "cktis-cpp-ref-exists";
const fs::path file = root / "item.txt";
std::error_code ignored;
fs::remove_all(root, ignored);
fs::create_directory(root);
std::ofstream(file) << "data";
std::error_code ec;
const bool present = fs::exists(file, ec);
const bool missing = fs::exists(root / "missing.txt", ec);
std::cout << present << ' ' << missing << ' ' << static_cast<bool>(ec) << '\n';
fs::remove_all(root, ignored);
}
Wynik
1 0 0
std::filesystem::exists → 1 0 0