Search code examples
c++eclipsefileeclipse-cdt

c++ not able to find file (i think)


I have the following code (simplified)

int main()
{
    ifstream myFile("input.txt");
    if(myFile.is_open())
        cout<<"test";
}

However myFile.is_open() is returning false;

why?

I'm using eclipse and the input.txt file is right in the src folder with the .cpp file...

Thanks!


Solution

  • Every executable is - by default - ran from the directory of your project. So for a tree like this:

    project
     |- src
     |  |- a.cpp
     |  |- b.cpp
     |  |- foo.txt
     |
     |- Debug
     |  |- a.exe
     |
     |- foo2.txt
    

    You shall use the paths like src/foo.txt or foo2.txt. Your exe is located in Debug directory, but it will be ran from your project's directory anyway. In this way, every build configuration's executables are ran in the same way (from the same place).

    You can change your working directory and arguments under Run configurations (pull-down menu next to the "run" icon). Switch to tab "Arguments", uncheck "use default" and set whichever you'd like if the default's not OK for you.