0

I am trying to compile a binary file that will open a txt file in the same directory that it is in next to it, read its components, store the first word into a string, and print it out. Here is the code:

#include <iostream>
#include <fstream>

int main(){
    std::ifstream is;
    is.open("text.txt");
    std::string s;
    if(is.fail()){
        std::cout << "Failed to open file" << std::endl;
        return 1;
    }
    is >> s;
    is.close();
    std::cout << "text gotten from file: " << s << std::endl;
    return 0;
}

my build command: clang++ main.cpp -o out

I am compiling this code with clang on Mac OS X Big Sur. This code compiles fine but the issue is that it will only read the txt file if ran from the command prompt with ./out. My goal is to make it so that if I double click on the exe the binary file will run in the directory that it is in. By default for some reason the directory that an application is run from on Mac OS is the home directory. I know this because I tried using an output stream instead of the input stream and it created the file under ~/ So my question is: Is there a way to make an executable binary run from the file that is in when double clicked?

Fahd
  • 43
  • 8

2 Answers2

0

Please use one of the solution provided in C++ Find execution path on Mac to find the path of executable and then you can use one of the solution from get directory from file path c++ and use it for your needs.

0

You can try like this for the find path;

ifstream file ("its your txt path", ios::in | ios::binary | ios::ate);

here is for the more information

Read binary file c++

I hope it's had be helpful.

Choi
  • 76
  • 1
  • 5