Skip to content

Instantly share code, notes, and snippets.

@malja
Last active May 28, 2018 20:27
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save malja/6d8ce3dbe39af056e0e690f8cdac3719 to your computer and use it in GitHub Desktop.
Save malja/6d8ce3dbe39af056e0e690f8cdac3719 to your computer and use it in GitHub Desktop.
Three methods for checking if file exists in C++.
#include <string>
#include <unistd.h>
// Funkce bere za parametr jméno souboru
bool fileExists(const std::string &file_name) {
// Pokud soubor existuje
if ( access( file_name.c_str(), F_OK ) != -1 ) {
// Vrátí true
return true;
// V opačném případě
} else {
// Vrátí false
return false;
}
} // bool fileExists()
#include <fstream>
#include <string>
// Funkce bere za parametr jméno souboru
bool fileExists(const std::string &file_name) {
// Pokusí se soubor otevřít
ifstream file(file_name.c_str());
// Pokud se otevření zdařilo
if (file.good()) {
// Uzavře soubor, uvolní paměť
file.close();
// a vrátí true
return true;
// Pokud se otevření nezdařilo\r\n
} else {
// Uzavře soubor, uvolní paměť
file.close();
// a vrátí false
return false;
}
} // bool fileExists()
#include <sys/stat.h>
#include <sys/types.h>
#include <iostream>
int main() {
// Struktura s informacemi o souboru
struct stat info;
// Pokud se načtení informací povedlo
if ( stat( "test.txt", &info ) == 0 ) {
std::cout << "Jde o soubor: " << S_ISREG(info.st_mode) << std::endl;
std::cout << "Jde o adresář:" << S_ISDIR(info.st_mode) << std::endl;
std::cout << "Velikost: " << info.st_size << "b" << std::endl;
std::cout << "Má vlastník právo na čtení: " << info.st_mode & S_IRUSR << std::endl;
std::cout << "Má vlastník právo ke spuštění: << info.st_mode & S_IXUSR << std::endl;
} else {
std::cout << "Soubor se nezdařilo otevřít" << std::endl;
std::cout << "Zkontrolujte, zda existuje, nebo zda není v adresáři, ke kterému nemáte přístup" << std::endl;
}
} // main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment