ifstream 为不存在的文件返回 true

ifstream returning true for files that don't exist

我想做什么?

我正在创建一个 c++ 程序,我正在检查是否存在文件以在 CWD(当前工作目录)中执行命令,如果不存在则 bin,如果不存在则 sbin 文件夹。

我在做什么?

我正在使用 ifstream 检查应用程序是否存在。如果创建了对象,我认为它是有效的。否则我不会。这是我所做的代码示例

string pathforCWD = argv[1];

ifstream checkFileCWD(pathforCWD.c_str());
        if (!checkFileCWD) {


    cout << "\nCommand not Found in working directory\n";
        cout<<endl<<"";
        string pathforBin = "/bin/",argv[1];
        ifstream checkFileBin(pathforBin.c_str());
        if(!checkFileBin)
        {
            cout<<"\nCommand also not found in Bin\n";
            string pathforSbin = "/sbin/",argv[1];

            ifstream checkFileSbin(pathforSbin.c_str());
                    if(!checkFileBin)
                    {
                        cout<<"\nFile also not found in sBin\n";
                    }
                    else
                    {
                        cout<<"\nCommand found in SBin directory.. Executing it."<<endl;
                        int response = system((orignalCommand).c_str());
                        programExecution(response);
                    }
        }
        else
        {
            cout<<"\nCommand found in Bin directory.. Executing it."<<endl;
            int response = system((orignalCommand).c_str());
            programExecution(response);
        }

    } else {
        cout<<"\nCommand found in working directory.. Executing it."<<endl;
        int response = system(("./" + orignalCommand).c_str());
        programExecution(response);
    }

我面临什么问题?

如果我将无效的程序名称参数传递给确实存在的程序。未创建当前工作目录 ifstram 对象,这意味着该文件不存在。怎么过/bin/。它说该对象每次都存在。即使没有。 我做错了什么?

以下定义与您认为的不一样:

string pathforBin = "/bin/",argv[1];

提示:您要在此处声明 两个 名称,pathforBinargv