Skip to content

Instantly share code, notes, and snippets.

@trojanfoe
Last active August 29, 2015 14:05
Show Gist options
  • Save trojanfoe/478f5604b3328a6e12f6 to your computer and use it in GitHub Desktop.
Save trojanfoe/478f5604b3328a6e12f6 to your computer and use it in GitHub Desktop.
Demonstrate changing the directory to the executable's path using C++
This is a one.
This is line two.
This is line three.
#include <iostream>
#include <fstream>
#include <string>
#include <unistd.h>
using namespace std;
int main(int argc, const char **argv)
{
string exename = argv[0];
string path = exename.substr(0, exename.find_last_of("/"));
cout << "Changing to directory '" << path << "'" << endl;
chdir(path.c_str());
ifstream file("file.txt");
string line;
while (getline(file, line))
cout << line << endl;
return 0;
}
--- Source/cpptinkering ‹master*➔ ?› » make
clang++ -DDEBUG=1 -g -Wall -std=c++11 -stdlib=libc++ -o setcwd setcwd.cpp -lstdc++
--- Source/cpptinkering ‹master*➔ ?› » ./setcwd
Changing to directory '.'
This is a one.
This is line two.
This is line three.
--- Source/cpptinkering ‹master*➔ ?› » cd /
--- / » /Users/andy/Source/cpptinkering/setcwd
Changing to directory '/Users/andy/Source/cpptinkering'
This is a one.
This is line two.
This is line three.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment