program tip

C ++에 파일이 있는지 확인하는 가장 좋은 방법은 무엇입니까?

radiobox 2020. 8. 26. 07:46
반응형

C ++에 파일이 있는지 확인하는 가장 좋은 방법은 무엇입니까? (크로스 플랫폼)


C에 파일이 있는지 확인하는 가장 좋은 방법무엇입니까?에 대한 답변을 읽었습니다 . (크로스 플랫폼) ,하지만 표준 C ++ 라이브러리를 사용하여이 작업을 수행하는 더 좋은 방법이 있는지 궁금합니다. 파일을 전혀 열지 않는 것이 좋습니다.

모두 stataccess거의 ungoogleable 있습니다. 이것을 어떻게 사용해야 #include합니까?


사용 부스트 : : 파일 시스템 :

#include <boost/filesystem.hpp>

if ( !boost::filesystem::exists( "myfile.txt" ) )
{
  std::cout << "Can't find my file!" << std::endl;
}

경합 상태에주의하십시오. "존재"확인과 파일을 여는 시간 사이에 파일이 사라지면 프로그램이 예기치 않게 실패합니다.

가서 파일을 열고 실패를 확인한 다음 모든 것이 정상이면 파일로 무언가를하는 것이 좋습니다. 보안에 중요한 코드에서는 훨씬 더 중요합니다.

보안 및 경쟁 조건에 대한 세부 사항 : http://www.ibm.com/developerworks/library/l-sprace.html


나는 행복한 부스트 사용자이며 확실히 Andreas의 솔루션을 사용할 것입니다. 그러나 부스트 라이브러리에 액세스 할 수없는 경우 스트림 라이브러리를 사용할 수 있습니다.

ifstream file(argv[1]);
if (!file)
{
    // Can't open file
}

파일이 실제로 열리기 때문에 boost :: filesystem :: exists만큼 좋지는 않지만 일반적으로 어쨌든 다음 작업을 수행합니다.


필요에 따라 충분히 크로스 플랫폼 인 경우 stat ()를 사용하십시오. 그래도 C ++ 표준은 아니지만 POSIX입니다.

MS Windows에는 _stat, _stat64, _stati64, _wstat, _wstat64, _wstati64가 있습니다.


어때요 access?

#include <io.h>

if (_access(filename, 0) == -1)
{
    // File does not exist
}

또 다른 가능성은 good()스트림 에서 함수 를 사용하는 것입니다.

#include <fstream>     
bool checkExistence(const char* filename)
{
     ifstream Infield(filename);
     return Infield.good();
}

파일이 존재하는지 알아 내려고 재검토 할 것입니다. 대신 사용하려는 것과 동일한 모드에서 (표준 C 또는 C ++에서) 열어야합니다. 파일을 사용해야 할 때 쓸 수없는 경우 파일이 존재한다는 것을 아는 것은 무슨 소용입니까?


NO 필수 될 것이라고, 과잉 .


다음과 같이 stat () (pavon에서 언급 한 것처럼 교차 플랫폼이 아님)을 사용하십시오.

#include <sys/stat.h>
#include <iostream>

// true if file exists
bool fileExists(const std::string& file) {
    struct stat buf;
    return (stat(file.c_str(), &buf) == 0);
}

int main() {
    if(!fileExists("test.txt")) {
        std::cerr << "test.txt doesn't exist, exiting...\n";
        return -1;
    }
    return 0;
}

산출:

C02QT2UBFVH6-lm:~ gsamaras$ ls test.txt
ls: test.txt: No such file or directory
C02QT2UBFVH6-lm:~ gsamaras$ g++ -Wall main.cpp
C02QT2UBFVH6-lm:~ gsamaras$ ./a.out
test.txt doesn't exist, exiting...

다른 버전 (및 저것)은 여기 에서 찾을 수 있습니다 .


컴파일러가 C ++ 17을 지원하는 경우 부스트가 필요하지 않습니다. std::filesystem::exists

#include <iostream> // only for std::cout
#include <filesystem>

if (!std::filesystem::exists("myfile.txt"))
{
    std::cout << "File not found!" << std::endl;
}

이미 입력 파일 스트림 클래스 ( ifstream)를 사용하고있는 경우 해당 함수를 사용할 수 있습니다 fail().

예:

ifstream myFile;

myFile.open("file.txt");

// Check for errors
if (myFile.fail()) {
    cerr << "Error: File could not be found";
    exit(1);
}

참고 URL : https://stackoverflow.com/questions/268023/what-s-the-best-way-to-check-if-a-file-exists-in-c-cross-platform

반응형