Search code examples
c++ubuntuauthenticationifstream

ifstream returning true for files that don't exist


What I am trying to do?

I'm creating a c++ program where I am checking as of the file exists for the execution of command in CWD (Current working directory) if not then bin and if not there then sbin folder.

What I am doing?

I am checking the existence of application using ifstream. If the object is created I consider it as valid. otherwise i don't. Here is a code sample of what I have done

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);
    }

What Issue I am facing?

If I pass an invalid program name argument to the program which does exist. The current working directory ifstram object is not created which means that file does not exist there. How ever for the /bin/. It says that the object exists each time. even if it doesn't. What I am doing wrong?


Solution

  • The following definition doesn't do what you think it does:

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

    Hint: you're declaring two names here, pathforBin and argv.