Last active
August 29, 2015 14:05
-
-
Save trojanfoe/478f5604b3328a6e12f6 to your computer and use it in GitHub Desktop.
Demonstrate changing the directory to the executable's path using C++
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This is a one. | |
This is line two. | |
This is line three. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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; | |
} |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
--- 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