C++ judge file whether exists

#include <iostream>

using namespace std;

void fileExist11();
void fileExist12();

int main()
{
    fileExist12();
    return 0;
}

void fileExist12()
{
    string fileName="log.txt";
    FILE *file=fopen(fileName.c_str(),"r");
    if(file!=nullptr)
    {
        cout<<fileName<<" exists!"<<endl;
        fclose(file);
    }
    else
    {
        cout<<fileName<<" not exist!"<<endl;
    }
    cout<<"fileExist12() finished!"<<endl;
}

void fileExist11()
{
    string fileName="log.txt";
    ifstream rFile(fileName.c_str());
    if(rFile.good())
    {
        cout<<fileName<<" existed!"<<endl;
    }
    else
    {
        cout<<fileName<<" not exist!"<<endl;
    }
    cout<<"fileExist11() finished!"<<endl;
}
g++ -g -std=c++2a -I. *.cpp -o h1 -lpthread -luuid

.Run compiled result

 

posted @ 2022-02-03 21:57  FredGrit  阅读(43)  评论(0编辑  收藏  举报