Important: Please read the Qt Code of Conduct -

Using ifstream on a Mac

  • Hi guys, I'm trying to access a file in the executable's directory. The file does not open with the code provided

    std::ifstream in;, std::ios_base::binary | std::ios_base::in);

    the message box outputs

    which leads me to believe that ifstream is using the wrong directory. I have a test file under "/Users/me/Qt/QtProjects/build-Desktop-Debug/" . What should I do to access the directory of my executable? Thanks!

  • Lifetime Qt Champion

  • @pacostacos said:

    fn is a parameter, type QString

  • Lifetime Qt Champion

    @pacostacos I mean what is its content? I guess it is the path to the file you want to open?
    And please check the link I provided: this way you can get the path to the directory where your executable is residing

  • Yes, fn stands for filename. it is the path to the file I want to open.
    Using QCoreApplication::applicationDirPath(), I obtain

    I have a test file under "/Users/me/Qt/QtProjects/build-Desktop-Debug/" named test.pdf that I want to open. The is in that folder.

    I actually just added the file to and it worked.... How do I include files in QT so they end up over there? thanks

  • The OS X applications (*.app) are actually folders but treated in a unique way. The function applicationDirPath() is actually returning the correct folder which is a sub folder of the application bundle where the real executable lives.

    I use this to deal with this situation:

    	QDir								data_location;
    	QString								data_path;
    	data_path = qApp->applicationDirPath();
    #ifdef Q_OS_MAC
    	int index = data_path.lastIndexOf(".app/");
    	index = data_path.lastIndexOf('/');

    The variable 'data_path' ends up with the location of the executable (non-OSX) or the folder of the .app bundle (OSX).

    One thing that I just realized looking at this code is that it will fail if the extension '.app' is not lower case (if that is even possible?). Maybe it should be something like this instead:

    int index = data_path.lastIndexOf(".app/",-1,Qt::CaseInsensitive);

  • Lifetime Qt Champion


    The quick and dirty way to do such testing is to add CONFIG -= app_bundle so you don't have the application bundle created and you'll be able to run your test.

    Just a side note: on OS X you should not have external resources in the same folder as the executable. It should be in folder name Resources in Contents.

  • @pacostacos said:

    I actually just added the file to and it worked.... How do I include files in QT so they end up over there? thanks

    Depending on what you want to achieve you can integrate the file as resource into your Qt application using the Qt resource system and access the file via qrc:/... so it will be available on all platforms via the same way (but only from inside our application).

Log in to reply