macOS iostream on a pseudo tty does not work - c++

GCC has a stdio_filebuf extension that lets you wrap an iostream around a file descriptor while clang's basic_filebuf has an __open() method that lets open a file descriptor. I've tested both on regular files on both linux and macos. Works as expected.
However, for a pseudo tty file descriptor, it works for linux but not macos. I've confirmed that the file descriptor on macos does work by using read(2) on it. Here's my code.
#include <fmt/format.h>
#include <getopt.h>
#include <vector>
#include <functional>
#include <future>
#include <fcntl.h>
#include <cstdlib>
#if defined(__linux__)
#include <ext/stdio_filebuf.h>
#elif defined(__APPLE__)
#include <fstream>
#else
#error "unsupported os"
#endif
#include <iostream>
#include <unistd.h>
int get_ptym(int oflags)
{
int fd;
if ((fd = posix_openpt(oflags)) == -1
or grantpt(fd) == -1
or unlockpt(fd) == -1)
return -1;
return fd;
}
ssize_t getdelim(int fd, char *buf, size_t bufsz,
char delim='\n', bool store_delim=false)
{
size_t j = 0;
while (j < bufsz-2) {
char c;
ssize_t rc;
if ((rc = ::read(fd, &c, 1)) == -1) return rc;
if (rc == 0) break;
if (c != delim) { buf[j++] = c; continue; }
// Break if we get the delimiter.
if (store_delim) buf[j++] = c;
break;
}
buf[j] = '\0';
return j+1;
}
std::string m0(int fd)
{
#if defined(__linux__)
__gnu_cxx::stdio_filebuf<char> fb(fd, std::ios::in|std::ios::out);
std::iostream ioob(&fb);
#endif
#if defined(__APPLE__)
std::basic_filebuf<char> fb;
std::iostream ioob(fb.__open(fd, std::ios::in|std::ios::out));
#endif
std::string s;
if (!std::getline(ioob, s, '\n').good())
throw std::runtime_error("m0: getline failed");
return s;
}
std::string m1(int fd)
{
char buf[4096];
ssize_t nrd;
if ((nrd = getdelim(fd, buf, sizeof(buf))) == -1)
throw std::runtime_error("getlim error");
return std::string(buf);
}
void testing(const std::string &foonm, std::function<std::string(int)> foo)
{
using namespace std::chrono_literals;
int mfd, sfd;
// Open pty master and slave.
if ((mfd = get_ptym(O_RDWR)) == -1) return;
if ((sfd = open(ptsname(mfd), O_RDWR)) == -1) return;
#if defined(__linux__)
__gnu_cxx::stdio_filebuf<char> fb(sfd, std::ios::in|std::ios::out);
std::iostream ioob(&fb);
#endif
#if defined(__APPLE__)
std::basic_filebuf<char> fb;
std::iostream ioob(fb.__open(sfd, std::ios::in|std::ios::out));
#endif
fmt::print("testing {}\n", foonm);
std::string s;
if (!std::getline(std::cin, s, '\n').good()) {
fmt::print("{}: getline failed\n", __func__);
return;
}
auto f = std::async(std::launch::async, foo, mfd);
ioob << s << '\n';
ioob.flush();
try {
std::string fget;
std::future_status fstatus;
fstatus = f.wait_for(8s);
switch (fstatus) {
case std::future_status::timeout:
fmt::print("{}: f.wait_for(8s) timed out\n", __func__);
break;
case std::future_status::ready:
fget = f.get();
fmt::print("{}: fstatus ready, f.get={}\n", __func__, fget);
break;
default:
fmt::print("{}: fstatus default??\n", __func__);
}
}
catch (std::exception &e) {
fmt::print("{}: exception \"{}\"\n", __func__, e.what());
}
}
int main(int argc, char *argv[])
{
testing("m1", m1);
testing("m0", m0);
return 0;
}
Any ideas?

Related

unshare user namespace, fork, map uid then execvp failing

I am trying to do the following sequence of actions:
unshare the user namespace;
Map the user in child process to root;
execvp.
However, when running id, my code outputs the user as a nobody or fails without error.
#include <sched.h>
#include <cstdio>
#include <cstring>
#include <cerrno>
#include <stdlib.h>
#include <unistd.h>
#include <sys/wait.h>
#include <sys/mount.h>
#include <system_error>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <stdio.h>
void unshare_user_namespace() {
if (0 != unshare(CLONE_NEWUSER)) {
fprintf(stderr, "%s\n", "USER unshare has failed");
exit(1);
}
}
void map_id() {
int pid = getpid();
char file[100];
if (0 > sprintf(file, "/proc/%d/uid_map", pid)) {
printf("Couldn't sprintf uid_map path.");
exit(1);
}
int fd;
fd = open(file, 1);
if (fd < 0) {
printf("Coudln't open file for writing.\n");
exit(1);
}
int uid = getuid();
char * buf;
if (0 > sprintf(buf, "0 %d 1", uid)) {
printf("Couldn't sprintf uid_map content.");
exit(1);
}
if (write(fd, buf, strlen(buf))) {
printf("Coudln't write mapping into file.\n");
exit(1);
}
free(buf);
close(fd);
}
void start(char * command, char ** args) {
unshare_user_namespace();
int fork_pid = fork();
if (-1 == fork_pid) {
fprintf(stderr, "%s\n", "couldn't fork");
exit(1);
}
if (0 == fork_pid) {
map_id();
if (-1 == execvp(command, args)) {
fprintf(stderr, "%s\n", "couldn't execvp");
exit(1);
}
}
}
int main(int argc, char ** argv) {
start(argv[1], & argv[1]);
int status;
wait( & status);
return 0;
}
I tried reading the man pages for namespaces, unshare etc but couldn't figure out what's wrong with my code.
To run the code:
$ g++ <file_containing_code> && ./a.out id
Pretty sure you've already found the answer, but this is a minimal sample I could come up with:
// gcc -Wall -std=c11
#define _GNU_SOURCE
#include <stdio.h>
#include <unistd.h>
#include <sched.h>
#include <sys/wait.h>
#include <stdlib.h>
#include <stdarg.h>
void write_to_file(const char *which, const char *format, ...) {
FILE * fu = fopen(which, "w");
va_list args;
va_start(args, format);
if (vfprintf(fu, format, args) < 0) {
perror("cannot write");
exit(1);
}
fclose(fu);
}
int main(int argc, char ** argv) {
// array of strings, terminated with NULL entry
char **cmd_and_args = (char**) calloc(argc, sizeof(char*));
for (int i = 1 ; i < argc; i++) {
cmd_and_args[i-1] = argv[i];
}
uid_t uid = getuid();
gid_t gid = getgid();
// first unshare
if (0 != unshare(CLONE_NEWUSER)) {
fprintf(stderr, "%s\n", "USER unshare has failed");
exit(1);
}
// remap uid
write_to_file("/proc/self/uid_map", "0 %d 1", uid);
// deny setgroups (see user_namespaces(7))
write_to_file("/proc/self/setgroups", "deny");
// remap gid
write_to_file("/proc/self/gid_map", "0 %d 1", gid);
// exec the command
if (execvp(cmd_and_args[0], cmd_and_args) < 0) {
perror("cannot execvp");
exit(1);
}
// unreachable
free(cmd_and_args);
return 0;
}

How to run a C++ exec file from the directory where it was called? [duplicate]

I know this question has been asked before but I still haven't seen a satisfactory answer, or a definitive "no, this cannot be done", so I'll ask again!
All I want to do is get the path to the currently running executable, either as an absolute path or relative to where the executable is invoked from, in a platform-independent fashion. I though boost::filesystem::initial_path was the answer to my troubles but that seems to only handle the 'platform-independent' part of the question - it still returns the path from which the application was invoked.
For a bit of background, this is a game using Ogre, which I'm trying to profile using Very Sleepy, which runs the target executable from its own directory, so of course on load the game finds no configuration files etc. and promptly crashes. I want to be able to pass it an absolute path to the configuration files, which I know will always live alongside the executable. The same goes for debugging in Visual Studio - I'd like to be able to run $(TargetPath) without having to set the working directory.
There is no cross platform way that I know.
For Linux: pass "/proc/self/exe" to std::filesystem::canonical or readlink.
Windows: pass NULL as the module handle to GetModuleFileName.
The boost::dll::program_location function is one of the best cross platform methods of getting the path of the running executable that I know of. The DLL library was added to Boost in version 1.61.0.
The following is my solution. I have tested it on Windows, Mac OS X, Solaris, Free BSD, and GNU/Linux.
It requires Boost 1.55.0 or greater. It uses the Boost.Filesystem library directly and the Boost.Locale library and Boost.System library indirectly.
src/executable_path.cpp
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
# include <boost/process.hpp>
#endif
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
# include <Windows.h>
#endif
#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>
namespace boost {
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector buf(1024, 0);
size_type size = buf.size();
bool havePath = false;
bool shouldContinue = true;
do
{
DWORD result = GetModuleFileNameA(nullptr, &buf[0], size);
DWORD lastError = GetLastError();
if (result == 0)
{
shouldContinue = false;
}
else if (result < size)
{
havePath = true;
shouldContinue = false;
}
else if (
result == size
&& (lastError == ERROR_INSUFFICIENT_BUFFER || lastError == ERROR_SUCCESS)
)
{
size *= 2;
buf.resize(size);
}
else
{
shouldContinue = false;
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
// On Microsoft Windows, there is no need to call boost::filesystem::canonical or
// boost::filesystem::path::make_preferred. The path returned by GetModuleFileNameA
// is the one we want.
std::string ret = &buf[0];
return ret;
}
#elif (BOOST_OS_MACOS)
# include <mach-o/dyld.h>
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
char_vector buf(1024, 0);
uint32_t size = static_cast<uint32_t>(buf.size());
bool havePath = false;
bool shouldContinue = true;
do
{
int result = _NSGetExecutablePath(&buf[0], &size);
if (result == -1)
{
buf.resize(size + 1);
std::fill(std::begin(buf), std::end(buf), 0);
}
else
{
shouldContinue = false;
if (buf.at(0) != 0)
{
havePath = true;
}
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#elif (BOOST_OS_SOLARIS)
# include <stdlib.h>
std::string executable_path(const char* argv0)
{
std::string ret = getexecname();
if (ret.empty())
{
return detail::executable_path_fallback(argv0);
}
boost::filesystem::path p(ret);
if (!p.has_root_directory())
{
boost::system::error_code ec;
p = boost::filesystem::canonical(
p, boost::filesystem::current_path(), ec);
if (ec.value() != boost::system::errc::success)
{
return detail::executable_path_fallback(argv0);
}
ret = p.make_preferred().string();
}
return ret;
}
#elif (BOOST_OS_BSD)
# include <sys/sysctl.h>
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
int mib[4]{0};
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
int result = sysctl(mib, 4, nullptr, &size, nullptr, 0);
if (-1 == result)
{
return detail::executable_path_fallback(argv0);
}
char_vector buf(size + 1, 0);
result = sysctl(mib, 4, &buf[0], &size, nullptr, 0);
if (-1 == result)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#elif (BOOST_OS_LINUX)
# include <unistd.h>
std::string executable_path(const char *argv0)
{
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector buf(1024, 0);
size_type size = buf.size();
bool havePath = false;
bool shouldContinue = true;
do
{
ssize_t result = readlink("/proc/self/exe", &buf[0], size);
if (result < 0)
{
shouldContinue = false;
}
else if (static_cast<size_type>(result) < size)
{
havePath = true;
shouldContinue = false;
size = result;
}
else
{
size *= 2;
buf.resize(size);
std::fill(std::begin(buf), std::end(buf), 0);
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#else
std::string executable_path(const char *argv0)
{
return detail::executable_path_fallback(argv0);
}
#endif
}
src/detail/executable_path_internals.cpp
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
# include <boost/process.hpp>
#endif
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
# include <Windows.h>
#endif
#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>
namespace boost {
namespace detail {
std::string GetEnv(const std::string& varName)
{
if (varName.empty()) return "";
#if (BOOST_OS_BSD || BOOST_OS_CYGWIN || BOOST_OS_LINUX || BOOST_OS_MACOS || BOOST_OS_SOLARIS)
char* value = std::getenv(varName.c_str());
if (!value) return "";
return value;
#elif (BOOST_OS_WINDOWS)
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector value(8192, 0);
size_type size = value.size();
bool haveValue = false;
bool shouldContinue = true;
do
{
DWORD result = GetEnvironmentVariableA(varName.c_str(), &value[0], size);
if (result == 0)
{
shouldContinue = false;
}
else if (result < size)
{
haveValue = true;
shouldContinue = false;
}
else
{
size *= 2;
value.resize(size);
}
} while (shouldContinue);
std::string ret;
if (haveValue)
{
ret = &value[0];
}
return ret;
#else
return "";
#endif
}
bool GetDirectoryListFromDelimitedString(
const std::string& str,
std::vector<std::string>& dirs)
{
typedef boost::char_separator<char> char_separator_type;
typedef boost::tokenizer<
boost::char_separator<char>, std::string::const_iterator,
std::string> tokenizer_type;
dirs.clear();
if (str.empty())
{
return false;
}
#if (BOOST_OS_WINDOWS)
const std::string os_pathsep(";");
#else
const std::string os_pathsep(":");
#endif
char_separator_type pathSep(os_pathsep.c_str());
tokenizer_type strTok(str, pathSep);
typename tokenizer_type::iterator strIt;
typename tokenizer_type::iterator strEndIt = strTok.end();
for (strIt = strTok.begin(); strIt != strEndIt; ++strIt)
{
dirs.push_back(*strIt);
}
if (dirs.empty())
{
return false;
}
return true;
}
std::string search_path(const std::string& file)
{
if (file.empty()) return "";
std::string ret;
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
{
namespace bp = boost::process;
boost::filesystem::path p = bp::search_path(file);
ret = p.make_preferred().string();
}
#endif
if (!ret.empty()) return ret;
// Drat! I have to do it the hard way.
std::string pathEnvVar = GetEnv("PATH");
if (pathEnvVar.empty()) return "";
std::vector<std::string> pathDirs;
bool getDirList = GetDirectoryListFromDelimitedString(pathEnvVar, pathDirs);
if (!getDirList) return "";
std::vector<std::string>::const_iterator it = pathDirs.cbegin();
std::vector<std::string>::const_iterator itEnd = pathDirs.cend();
for ( ; it != itEnd; ++it)
{
boost::filesystem::path p(*it);
p /= file;
if (boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p))
{
return p.make_preferred().string();
}
}
return "";
}
std::string executable_path_fallback(const char *argv0)
{
if (argv0 == nullptr) return "";
if (argv0[0] == 0) return "";
#if (BOOST_OS_WINDOWS)
const std::string os_sep("\\");
#else
const std::string os_sep("/");
#endif
if (strstr(argv0, os_sep.c_str()) != nullptr)
{
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
argv0, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
}
std::string ret = search_path(argv0);
if (!ret.empty())
{
return ret;
}
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
argv0, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
ret = p.make_preferred().string();
}
return ret;
}
}
}
include/boost/executable_path.hpp
#ifndef BOOST_EXECUTABLE_PATH_HPP_
#define BOOST_EXECUTABLE_PATH_HPP_
#pragma once
#include <string>
namespace boost {
std::string executable_path(const char * argv0);
}
#endif // BOOST_EXECUTABLE_PATH_HPP_
include/boost/detail/executable_path_internals.hpp
#ifndef BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
#define BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
#pragma once
#include <string>
#include <vector>
namespace boost {
namespace detail {
std::string GetEnv(const std::string& varName);
bool GetDirectoryListFromDelimitedString(
const std::string& str,
std::vector<std::string>& dirs);
std::string search_path(const std::string& file);
std::string executable_path_fallback(const char * argv0);
}
}
#endif // BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
I have a complete project, including a test application and CMake build files available at SnKOpen - /cpp/executable_path/trunk. This version is more complete than the version I provided here. It is also supports more platforms.
I have tested the application on all supported operating systems in the following four scenarios.
Relative path, executable in current directory: i.e. ./executable_path_test
Relative path, executable in another directory: i.e. ./build/executable_path_test
Full path: i.e. /some/dir/executable_path_test
Executable in path, file name only: i.e. executable_path_test
In all four scenarios, both the executable_path and executable_path_fallback functions work and return the same results.
Notes
This is an updated answer to this question. I updated the answer to take into consideration user comments and suggestions. I also added a link to a project in my SVN Repository.
This way uses boost + argv. You mentioned this may not be cross platform because it may or may not include the executable name. Well the following code should work around that.
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc,char** argv)
{
fs::path full_path( fs::initial_path<fs::path>() );
full_path = fs::system_complete( fs::path( argv[0] ) );
std::cout << full_path << std::endl;
//Without file name
std::cout << full_path.stem() << std::endl;
//std::cout << fs::basename(full_path) << std::endl;
return 0;
}
The following code gets the current working directory which may do what you need
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc,char** argv)
{
//current working directory
fs::path full_path( fs::current_path<fs::path>() );
std::cout << full_path << std::endl;
std::cout << full_path.stem() << std::endl;
//std::cout << fs::basepath(full_path) << std::endl;
return 0;
}
Note
Just realized that basename() was deprecated so had to switch to .stem()
C++17, windows, unicode, using filesystem new api:
#include "..\Project.h"
#include <filesystem>
using namespace std;
using namespace filesystem;
int wmain(int argc, wchar_t** argv)
{
auto dir = weakly_canonical(path(argv[0])).parent_path();
printf("%S", dir.c_str());
return 0;
}
(Important: Use wmain with wchar_t** - don't mix main with wchar_t**. For cmake projects enable unicode using add_definitions(-DUNICODE -D_UNICODE)).
Suspect this solution should be portable, but don't know how unicode is implemented on other OS's.
weakly_canonical is needed only if you use as Output Directory upper folder references ('..') to simplify path. If you don't use it - remove it.
If you're operating from dynamic link library (.dll /.so), then you might not have argv, then you can consider following solution:
application.h:
#pragma once
//
// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
//
#ifdef __cpp_lib_filesystem
#include <filesystem>
#else
#include <experimental/filesystem>
namespace std {
namespace filesystem = experimental::filesystem;
}
#endif
std::filesystem::path getexepath();
application.cpp:
#include "application.h"
#ifdef _WIN32
#include <windows.h> //GetModuleFileNameW
#else
#include <limits.h>
#include <unistd.h> //readlink
#endif
std::filesystem::path getexepath()
{
#ifdef _WIN32
wchar_t path[MAX_PATH] = { 0 };
GetModuleFileNameW(NULL, path, MAX_PATH);
return path;
#else
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
return std::string(result, (count > 0) ? count : 0);
#endif
}
I'm not sure about Linux, but try this for Windows:
#include <windows.h>
#include <iostream>
using namespace std ;
int main()
{
char ownPth[MAX_PATH];
// When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
HMODULE hModule = GetModuleHandle(NULL);
if (hModule != NULL)
{
// Use GetModuleFileName() with module handle to get the path
GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
cout << ownPth << endl ;
system("PAUSE");
return 0;
}
else
{
cout << "Module handle is NULL" << endl ;
system("PAUSE");
return 0;
}
}
This is what I ended up with
The header file looks like this:
#pragma once
#include <string>
namespace MyPaths {
std::string getExecutablePath();
std::string getExecutableDir();
std::string mergePaths(std::string pathA, std::string pathB);
bool checkIfFileExists (const std::string& filePath);
}
Implementation
#if defined(_WIN32)
#include <windows.h>
#include <Shlwapi.h>
#include <io.h>
#define access _access_s
#endif
#ifdef __APPLE__
#include <libgen.h>
#include <limits.h>
#include <mach-o/dyld.h>
#include <unistd.h>
#endif
#ifdef __linux__
#include <limits.h>
#include <libgen.h>
#include <unistd.h>
#if defined(__sun)
#define PROC_SELF_EXE "/proc/self/path/a.out"
#else
#define PROC_SELF_EXE "/proc/self/exe"
#endif
#endif
namespace MyPaths {
#if defined(_WIN32)
std::string getExecutablePath() {
char rawPathName[MAX_PATH];
GetModuleFileNameA(NULL, rawPathName, MAX_PATH);
return std::string(rawPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char* exePath = new char[executablePath.length()];
strcpy(exePath, executablePath.c_str());
PathRemoveFileSpecA(exePath);
std::string directory = std::string(exePath);
delete[] exePath;
return directory;
}
std::string mergePaths(std::string pathA, std::string pathB) {
char combined[MAX_PATH];
PathCombineA(combined, pathA.c_str(), pathB.c_str());
std::string mergedPath(combined);
return mergedPath;
}
#endif
#ifdef __linux__
std::string getExecutablePath() {
char rawPathName[PATH_MAX];
realpath(PROC_SELF_EXE, rawPathName);
return std::string(rawPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char *executablePathStr = new char[executablePath.length() + 1];
strcpy(executablePathStr, executablePath.c_str());
char* executableDir = dirname(executablePathStr);
delete [] executablePathStr;
return std::string(executableDir);
}
std::string mergePaths(std::string pathA, std::string pathB) {
return pathA+"/"+pathB;
}
#endif
#ifdef __APPLE__
std::string getExecutablePath() {
char rawPathName[PATH_MAX];
char realPathName[PATH_MAX];
uint32_t rawPathSize = (uint32_t)sizeof(rawPathName);
if(!_NSGetExecutablePath(rawPathName, &rawPathSize)) {
realpath(rawPathName, realPathName);
}
return std::string(realPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char *executablePathStr = new char[executablePath.length() + 1];
strcpy(executablePathStr, executablePath.c_str());
char* executableDir = dirname(executablePathStr);
delete [] executablePathStr;
return std::string(executableDir);
}
std::string mergePaths(std::string pathA, std::string pathB) {
return pathA+"/"+pathB;
}
#endif
bool checkIfFileExists (const std::string& filePath) {
return access( filePath.c_str(), 0 ) == 0;
}
}
For windows:
GetModuleFileName - returns the exe path + exe filename
To remove filename
PathRemoveFileSpec
QT provides this with OS abstraction as QCoreApplication::applicationDirPath()
If using C++17 one can do the following to get the path to the executable.
#include <filesystem>
std::filesystem::path getExecutablePath()
{
return std::filesystem::canonical("/proc/self/exe");
}
The above answer has been tested on Debian 10 using G++ 9.3.0
This is a Windows specific way, but it is at least half of your answer.
GetThisPath.h
/// dest is expected to be MAX_PATH in length.
/// returns dest
/// TCHAR dest[MAX_PATH];
/// GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
GetThisPath.cpp
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
if (!dest) return NULL;
if (MAX_PATH > destSize) return NULL;
DWORD length = GetModuleFileName( NULL, dest, destSize );
PathRemoveFileSpec(dest);
return dest;
}
mainProgram.cpp
TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
I would suggest using platform detection as preprocessor directives to change the implementation of a wrapper function that calls GetThisPath for each platform.
Using args[0] and looking for '/' (or '\\'):
#include <string>
#include <iostream> // to show the result
int main( int numArgs, char *args[])
{
// Get the last position of '/'
std::string aux(args[0]);
// get '/' or '\\' depending on unix/mac or windows.
#if defined(_WIN32) || defined(WIN32)
int pos = aux.rfind('\\');
#else
int pos = aux.rfind('/');
#endif
// Get the path and the name
std::string path = aux.substr(0,pos+1);
std::string name = aux.substr(pos+1);
// show results
std::cout << "Path: " << path << std::endl;
std::cout << "Name: " << name << std::endl;
}
EDITED:
If '/' does not exist, pos==-1 so the result is correct.
For Windows you can use GetModuleFilename().
For Linux see BinReloc (old, defunct URL) mirror of BinReloc in datenwolf's GitHub repositories.
This is probably the most natural way to do it, while covering most major desktop platforms. I am not certain, but I believe this should work with all the BSD's, not just FreeBSD, if you change the platform macro check to cover all of them. If I ever get around to installing Solaris, I'll be sure to add that platform to the supported list.
Features full UTF-8 support on Windows, which not everyone cares enough to go that far.
procinfo/win32/procinfo.cpp
#ifdef _WIN32
#include "../procinfo.h"
#include <windows.h>
#include <tlhelp32.h>
#include <cstddef>
#include <vector>
#include <cwchar>
using std::string;
using std::wstring;
using std::vector;
using std::size_t;
static inline string narrow(wstring wstr) {
int nbytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), NULL, 0, NULL, NULL);
vector<char> buf(nbytes);
return string{ buf.data(), (size_t)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), buf.data(), nbytes, NULL, NULL) };
}
process_t ppid_from_pid(process_t pid) {
process_t ppid;
HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hp, &pe)) {
do {
if (pe.th32ProcessID == pid) {
ppid = pe.th32ParentProcessID;
break;
}
} while (Process32Next(hp, &pe));
}
CloseHandle(hp);
return ppid;
}
string path_from_pid(process_t pid) {
string path;
HANDLE hm = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
MODULEENTRY32W me = { 0 };
me.dwSize = sizeof(MODULEENTRY32W);
if (Module32FirstW(hm, &me)) {
do {
if (me.th32ProcessID == pid) {
path = narrow(me.szExePath);
break;
}
} while (Module32NextW(hm, &me));
}
CloseHandle(hm);
return path;
}
#endif
procinfo/macosx/procinfo.cpp
#if defined(__APPLE__) && defined(__MACH__)
#include "../procinfo.h"
#include <libproc.h>
using std::string;
string path_from_pid(process_t pid) {
string path;
char buffer[PROC_PIDPATHINFO_MAXSIZE];
if (proc_pidpath(pid, buffer, sizeof(buffer)) > 0) {
path = string(buffer) + "\0";
}
return path;
}
#endif
procinfo/linux/procinfo.cpp
#ifdef __linux__
#include "../procinfo.h"
#include <cstdlib>
using std::string;
using std::to_string;
string path_from_pid(process_t pid) {
string path;
string link = string("/proc/") + to_string(pid) + string("/exe");
char *buffer = realpath(link.c_str(), NULL);
path = buffer ? : "";
free(buffer);
return path;
}
#endif
procinfo/freebsd/procinfo.cpp
#ifdef __FreeBSD__
#include "../procinfo.h"
#include <sys/sysctl.h>
#include <cstddef>
using std::string;
using std::size_t;
string path_from_pid(process_t pid) {
string path;
size_t length;
// CTL_KERN::KERN_PROC::KERN_PROC_PATHNAME(pid)
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, pid };
if (sysctl(mib, 4, NULL, &length, NULL, 0) == 0) {
path.resize(length, '\0');
char *buffer = path.data();
if (sysctl(mib, 4, buffer, &length, NULL, 0) == 0) {
path = string(buffer) + "\0";
}
}
return path;
}
#endif
procinfo/procinfo.cpp
#include "procinfo.h"
#ifdef _WiN32
#include <process.h>
#endif
#include <unistd.h>
#include <cstddef>
using std::string;
using std::size_t;
process_t pid_from_self() {
#ifdef _WIN32
return _getpid();
#else
return getpid();
#endif
}
process_t ppid_from_self() {
#ifdef _WIN32
return ppid_from_pid(pid_from_self());
#else
return getppid();
#endif
}
string dir_from_pid(process_t pid) {
string fname = path_from_pid(pid);
size_t fp = fname.find_last_of("/\\");
return fname.substr(0, fp + 1);
}
string name_from_pid(process_t pid) {
string fname = path_from_pid(pid);
size_t fp = fname.find_last_of("/\\");
return fname.substr(fp + 1);
}
procinfo/procinfo.h
#ifdef _WiN32
#include <windows.h>
typedef DWORD process_t;
#else
#include <sys/types.h>
typedef pid_t process_t;
#endif
#include <string>
/* windows-only helper function */
process_t ppid_from_pid(process_t pid);
/* get current process process id */
process_t pid_from_self();
/* get parent process process id */
process_t ppid_from_self();
/* std::string possible_result = "C:\\path\\to\\file.exe"; */
std::string path_from_pid(process_t pid);
/* std::string possible_result = "C:\\path\\to\\"; */
std::string dir_from_pid(process_t pid);
/* std::string possible_result = "file.exe"; */
std::string name_from_pid(process_t pid);
This allows getting the full path to the executable of pretty much any process id, except on Windows there are some process's with security attributes which simply will not allow it, so wysiwyg, this solution is not perfect.
To address what the question was asking more precisely, you may do this:
procinfo.cpp
#include "procinfo/procinfo.h"
#include <iostream>
using std::string;
using std::cout;
using std::endl;
int main() {
cout << dir_from_pid(pid_from_self()) << endl;
return 0;
}
Build the above file structure with this command:
procinfo.sh
cd "${0%/*}"
g++ procinfo.cpp procinfo/procinfo.cpp procinfo/win32/procinfo.cpp procinfo/macosx/procinfo.cpp procinfo/linux/procinfo.cpp procinfo/freebsd/procinfo.cpp -o procinfo.exe
For downloading a copy of the files listed above:
git clone git://github.com/time-killer-games/procinfo.git
For more cross-platform process-related goodness:
https://github.com/time-killer-games/enigma-dev
See the readme for a list of most of the functions included.
As others mentioned, argv[0] is quite a nice solution, provided that the platform actually passes the executable path, which is surely not less probable than the OS being Windows (where WinAPI can help find the executable path). If you want to strip the string to only include the path to the directory where the executable resides, then using that path to find other application files (like game assets if your program is a game) is perfectly fine, since opening files is relative to the working directory, or, if provided, the root.
The following works as a quick and dirty solution, but note that it is far from being foolproof:
#include <iostream>
using namespace std ;
int main( int argc, char** argv)
{
cout << argv[0] << endl ;
return 0;
}
In case you need to handle unicode paths for Windows:
#include <Windows.h>
#include <iostream>
int wmain(int argc, wchar_t * argv[])
{
HMODULE this_process_handle = GetModuleHandle(NULL);
wchar_t this_process_path[MAX_PATH];
GetModuleFileNameW(NULL, this_process_path, sizeof(this_process_path));
std::wcout << "Unicode path of this app: " << this_process_path << std::endl;
return 0;
}
There are several answers recommending using GetModuleFileName on Windows. These answers have some shortcomings like:
The code should work for both UNICODE and ANSI versions
The path can be longer than MAX_PATH
GetModuleFileName function can fail and return 0
GetModuleFileName can return a relative executable name instead of a full name
GetModuleFileName can return a short path like C:\GIT-RE~1\TEST_G~1\test.exe
Let me provide an improved version, which takes into account the abovementioned points:
#include <Windows.h>
#include <string>
#include <memory>
#include <iostream>
// Converts relative name like "..\test.exe" to its full form like "C:\project\test.exe".
std::basic_string<TCHAR> get_full_name(const TCHAR const* name)
{
// First we need to get a length of the full name string
const DWORD full_name_length{GetFullPathName(name, 0, NULL, NULL)};
if (full_name_length == 0) {
// GetFullPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// Now, when we know the length, we create a buffer with correct size and write the full name into it
std::unique_ptr<TCHAR[]> full_name_buffer{new TCHAR[full_name_length]};
const DWORD res = GetFullPathName(name, full_name_length, full_name_buffer.get(), NULL);
if (res == 0) {
// GetFullPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// The full name has been successfully written to the buffer.
return std::basic_string<TCHAR>(full_name_buffer.get());
}
// Resolves short path like "C:\GIT-RE~1\TEST_G~1\test.exe" into its long form like "C:\git-repository\test_project\test.exe"
std::basic_string<TCHAR> get_long_name(const TCHAR const* name)
{
// First we need to get a length of the long name string
const DWORD long_name_length{GetLongPathName(name, 0, NULL)};
if (long_name_length == 0) {
// GetLongPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// Now, when we know the length, we create a buffer with correct size and write the full name into it
std::unique_ptr<TCHAR[]> long_name_buffer{new TCHAR[long_name_length]};
const DWORD res = GetLongPathName(name, long_name_buffer.get(), long_name_length);
if (res == 0) {
// GetLongPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// The long name has been successfully written to the buffer.
return std::basic_string<TCHAR>(long_name_buffer.get());
}
std::basic_string<TCHAR> get_current_executable_full_name()
{
DWORD path_buffer_size = MAX_PATH; // we start with MAX_PATH because it is most likely that
// the path doesn't exceeds 260 characters
std::unique_ptr<TCHAR[]> path_buffer{new TCHAR[path_buffer_size]};
while (true) {
const auto bytes_written = GetModuleFileName(
NULL, path_buffer.get(), path_buffer_size);
const auto last_error = GetLastError();
if (bytes_written == 0) {
// GetModuleFileName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
if (last_error == ERROR_INSUFFICIENT_BUFFER) {
// There is not enough space in our buffer to fit the path.
// We need to increase the buffer and try again.
path_buffer_size *= 2;
path_buffer.reset(new TCHAR[path_buffer_size]);
continue;
}
// GetModuleFileName has successfully written the executable name to the buffer.
// Now we need to convert it to a full long name
std::basic_string<TCHAR> full_name = get_full_name(path_buffer.get());
return get_long_name(full_name.c_str());
}
}
// Example of how this function can be used
int main()
{
#ifdef UNICODE
// If you use UNICODE version of WinApi
std::wstring exe_file_full_name = get_current_executable_full_name();
std::wstring exe_folder_full_name = exe_file_full_name.substr(0, exe_file_full_name.find_last_of(L"\\"));
std::wcout << exe_file_full_name << "\n"; // prints: C:\test_project\x64\Debug\test_program.exe
std::wcout << exe_folder_full_name << "\n"; // prints: C:\test_project\x64\Debug
#else
// If you use ANSI version of WinApi
std::string exe_file_full_name = get_current_executable_full_name();
std::string exe_folder_full_name = exe_file_full_name.substr(0, exe_file_full_name.find_last_of("\\"));
std::cout << exe_file_full_name << "\n"; // prints: C:\test_project\x64\Debug\test_program.exe
std::cout << exe_folder_full_name << "\n"; // prints: C:\test_project\x64\Debug
#endif
}
For Windows, you have the problem of how to strip the executable from the result of GetModuleFileName(). The Windows API call PathRemoveFileSpec() that Nate used for that purpose in his answer changed between Windows 8 and its predecessors. So how to remain compatible with both and safe? Luckily, there's C++17 (or Boost, if you're using an older compiler). I do this:
#include <windows.h>
#include <string>
#include <filesystem>
namespace fs = std::experimental::filesystem;
// We could use fs::path as return type, but if you're not aware of
// std::experimental::filesystem, you probably handle filenames
// as strings anyway in the remainder of your code. I'm on Japanese
// Windows, so wide chars are a must.
std::wstring getDirectoryWithCurrentExecutable()
{
int size = 256;
std::vector<wchar_t> charBuffer;
// Let's be safe, and find the right buffer size programmatically.
do {
size *= 2;
charBuffer.resize(size);
// Resize until filename fits. GetModuleFileNameW returns the
// number of characters written to the buffer, so if the
// return value is smaller than the size of the buffer, it was
// large enough.
} while (GetModuleFileNameW(NULL, charBuffer.data(), size) == size);
// Typically: c:/program files (x86)/something/foo/bar/exe/files/win64/baz.exe
// (Note that windows supports forward and backward slashes as path
// separators, so you have to be careful when searching through a path
// manually.)
// Let's extract the interesting part:
fs::path path(charBuffer.data()); // Contains the full path including .exe
return path.remove_filename() // Extract the directory ...
.w_str(); // ... and convert to a string.
}
SDL2 (https://www.libsdl.org/) library has two functions implemented across a wide spectrum of platforms:
SDL_GetBasePath
SDL_GetPrefPath
So if you don't want to reinvent the wheel... sadly, it means including the entire library, although it's got a quite permissive license and one could also just copy the code. Besides, it provides a lot of other cross-platform functionality.
I didn't read if my solution is already posted but on linux and osx you can read the 0 argument in your main function like this:
int main(int argument_count, char **argument_list) {
std::string currentWorkingDirectoryPath(argument_list[currentWorkingDirectory]);
std::size_t pos = currentWorkingDirectoryPath.rfind("/"); // position of "live" in str
currentWorkingDirectoryPath = currentWorkingDirectoryPath.substr (0, pos);
In the first item of argument_list the name of the executable is integrated but removed by the code above.
Here my simple solution that works in both Windows and Linux, based on this solution and modified with this answer:
#include <string>
using namespace std;
#if defined(_WIN32)
#include <algorithm> // for transform() in get_exe_path()
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
#elif defined(__linux__)
#include <unistd.h> // for getting path of executable
#endif // Windows/Linux
string replace(const string& s, const string& from, const string& to) {
string r = s;
int p = 0;
while((p=(int)r.find(from, p))!=string::npos) {
r.replace(p, from.length(), to);
p += (int)to.length();
}
return r;
}
string get_exe_path() { // returns path where executable is located
string path = "";
#if defined(_WIN32)
wchar_t wc[260] = {0};
GetModuleFileNameW(NULL, wc, 260);
wstring ws(wc);
transform(ws.begin(), ws.end(), back_inserter(path), [](wchar_t c) { return (char)c; });
path = replace(path, "\\", "/");
#elif defined(__linux__)
char c[260];
int length = (int)readlink("/proc/self/exe", c, 260);
path = string(c, length>0 ? length : 0);
#endif // Windows/Linux
return path.substr(0, path.rfind('/')+1);
}
This was my solution in Windows. It is called like this:
std::wstring sResult = GetPathOfEXE(64);
Where 64 is the minimum size you think the path will be. GetPathOfEXE calls itself recursively, doubling the size of the buffer each time until it gets a big enough buffer to get the whole path without truncation.
std::wstring GetPathOfEXE(DWORD dwSize)
{
WCHAR* pwcharFileNamePath;
DWORD dwLastError;
HRESULT hrError;
std::wstring wsResult;
DWORD dwCount;
pwcharFileNamePath = new WCHAR[dwSize];
dwCount = GetModuleFileNameW(
NULL,
pwcharFileNamePath,
dwSize
);
dwLastError = GetLastError();
if (ERROR_SUCCESS == dwLastError)
{
hrError = PathCchRemoveFileSpec(
pwcharFileNamePath,
dwCount
);
if (S_OK == hrError)
{
wsResult = pwcharFileNamePath;
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
return wsResult;
}
else if(S_FALSE == hrError)
{
wsResult = pwcharFileNamePath;
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
//there was nothing to truncate off the end of the path
//returning something better than nothing in this case for the user
return wsResult;
}
else
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
std::ostringstream oss;
oss << "could not get file name and path of executing process. error truncating file name off path. last error : " << hrError;
throw std::runtime_error(oss.str().c_str());
}
}
else if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
return GetPathOfEXE(
dwSize * 2
);
}
else
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
std::ostringstream oss;
oss << "could not get file name and path of executing process. last error : " << dwLastError;
throw std::runtime_error(oss.str().c_str());
}
}
char exePath[512];
CString strexePath;
GetModuleFileName(NULL,exePath,512);
strexePath.Format("%s",exePath);
strexePath = strexePath.Mid(0,strexePath.ReverseFind('\\'));
in Unix(including Linux) try 'which', in Windows try 'where'.
#include <stdio.h>
#define _UNIX
int main(int argc, char** argv)
{
char cmd[128];
char buf[128];
FILE* fp = NULL;
#if defined(_UNIX)
sprintf(cmd, "which %s > my.path", argv[0]);
#else
sprintf(cmd, "where %s > my.path", argv[0]);
#endif
system(cmd);
fp = fopen("my.path", "r");
fgets(buf, sizeof(buf), fp);
fclose(fp);
printf("full path: %s\n", buf);
unlink("my.path");
return 0;
}
As of C++17:
Make sure you include std filesystem.
#include <filesystem>
and now you can do this.
std::filesystem::current_path().string()
boost filesystem became part of the standard lib.
if you can't find it try to look under:
std::experimental::filesystem

Can't invoke g++ with redirected stdout

I'm looking to invoke g++ and get the output. Here's my code:
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <boost/optional.hpp>
#include <vector>
#include <string>
namespace Util
{
template<typename T>
using optional = boost::optional<T>;
}
namespace Wide
{
namespace Driver
{
struct ProcessResult
{
std::string std_out;
int exitcode;
};
ProcessResult StartAndWaitForProcess(std::string name, std::vector<std::string> args, Util::optional<unsigned> timeout);
}
}
#include <unistd.h>
#include <sys/types.h>
#include <sys/wait.h>
#include <iostream>
#include <fcntl.h>
Wide::Driver::ProcessResult Wide::Driver::StartAndWaitForProcess(std::string name, std::vector<std::string> args, Util::optional<unsigned> timeout) {
int filedes[2];
pipe(filedes);
pid_t pid = fork();
if (pid == 0) {
while ((dup2(filedes[1], STDOUT_FILENO) == -1) && (errno == EINTR)) {}
auto fd = open("/dev/null", O_RDWR);
while ((dup2(fd, STDIN_FILENO) == -1) && (errno == EINTR)) {}
//freopen("/dev/null", "rw", stdin);
//freopen("/dev/null", "rw", stderr);
//close(filedes[1]);
close(filedes[0]);
std::vector<const char*> cargs;
cargs.push_back(name.c_str());
for (auto&& arg : args)
cargs.push_back(arg.c_str());
cargs.push_back(nullptr);
execv(name.c_str(), const_cast<char* const*>(&cargs[0]));
}
std::string std_out;
close(filedes[1]);
char buffer[4096];
while (1) {
ssize_t count = read(filedes[0], buffer, sizeof(buffer));
if (count == -1) {
if (errno == EINTR) {
continue;
} else {
perror("read");
exit(1);
}
} else if (count == 0) {
break;
} else {
std_out += std::string(buffer, buffer + count);
}
}
close(filedes[0]);
int status;
ProcessResult result;
result.std_out = std_out;
waitpid(pid, &status, 0);
if (!WIFEXITED(status))
result.exitcode = 1;
else {
result.exitcode = WEXITSTATUS(status);
if (result.exitcode != 0) {
std::cout << name << " failed with code " << result.exitcode << "\n";
}
}
return result;
}
int main()
{
auto r = Wide::Driver::StartAndWaitForProcess("g++", { "-std=c++14", "main.cpp" }, 150);
std::cout << r.std_out << "!!!!\n!!!!\n" << r.exitcode << "\n";
}
The output:
read: Bad file descriptor
g++ failed with code 1
!!!!
!!!!
1
Just invoke g++ main.cpp -std=c++14 && ./a.out.
I've used strace but it doesn't really give any more interesting details- the process runs, then fork/exec, then the above error. I can invoke other processes with the above code so I don't know what's so different about g++. I can invoke GCC with popen without problems so I don't know what's so different here.
The error here is really not very helpful. How can I invoke g++ and get the output?
The problem here is that you call execv which requires a full path to the executable as its first argument.
What you need is execvp which uses the contents of the PATH environment variable to find the executable, and thus only requires a name like g++.

redirect stdout/stderr to a string

there has been many previous questions about redirecting stdout/stderr to a file. is there a way to redirect stdout/stderr to a string?
Yes, you can redirect it to an std::stringstream:
std::stringstream buffer;
std::streambuf * old = std::cout.rdbuf(buffer.rdbuf());
std::cout << "Bla" << std::endl;
std::string text = buffer.str(); // text will now contain "Bla\n"
You can use a simple guard class to make sure the buffer is always reset:
struct cout_redirect {
cout_redirect( std::streambuf * new_buffer )
: old( std::cout.rdbuf( new_buffer ) )
{ }
~cout_redirect( ) {
std::cout.rdbuf( old );
}
private:
std::streambuf * old;
};
You can use this class:
#include <unistd.h>
#include <fcntl.h>
#include <stdio.h>
#include <string>
class StdCapture
{
public:
StdCapture(): m_capturing(false), m_init(false), m_oldStdOut(0), m_oldStdErr(0)
{
m_pipe[READ] = 0;
m_pipe[WRITE] = 0;
if (_pipe(m_pipe, 65536, O_BINARY) == -1)
return;
m_oldStdOut = dup(fileno(stdout));
m_oldStdErr = dup(fileno(stderr));
if (m_oldStdOut == -1 || m_oldStdErr == -1)
return;
m_init = true;
}
~StdCapture()
{
if (m_capturing)
{
EndCapture();
}
if (m_oldStdOut > 0)
close(m_oldStdOut);
if (m_oldStdErr > 0)
close(m_oldStdErr);
if (m_pipe[READ] > 0)
close(m_pipe[READ]);
if (m_pipe[WRITE] > 0)
close(m_pipe[WRITE]);
}
void BeginCapture()
{
if (!m_init)
return;
if (m_capturing)
EndCapture();
fflush(stdout);
fflush(stderr);
dup2(m_pipe[WRITE], fileno(stdout));
dup2(m_pipe[WRITE], fileno(stderr));
m_capturing = true;
}
bool EndCapture()
{
if (!m_init)
return false;
if (!m_capturing)
return false;
fflush(stdout);
fflush(stderr);
dup2(m_oldStdOut, fileno(stdout));
dup2(m_oldStdErr, fileno(stderr));
m_captured.clear();
std::string buf;
const int bufSize = 1024;
buf.resize(bufSize);
int bytesRead = 0;
if (!eof(m_pipe[READ]))
{
bytesRead = read(m_pipe[READ], &(*buf.begin()), bufSize);
}
while(bytesRead == bufSize)
{
m_captured += buf;
bytesRead = 0;
if (!eof(m_pipe[READ]))
{
bytesRead = read(m_pipe[READ], &(*buf.begin()), bufSize);
}
}
if (bytesRead > 0)
{
buf.resize(bytesRead);
m_captured += buf;
}
m_capturing = false;
return true;
}
std::string GetCapture() const
{
std::string::size_type idx = m_captured.find_last_not_of("\r\n");
if (idx == std::string::npos)
{
return m_captured;
}
else
{
return m_captured.substr(0, idx+1);
}
}
private:
enum PIPES { READ, WRITE };
int m_pipe[2];
int m_oldStdOut;
int m_oldStdErr;
bool m_capturing;
bool m_init;
std::string m_captured;
};
call BeginCapture() when you need to start capture
call EndCapture() when you need to stop capture
call GetCapture() to retrieve captured output
In order to provide a thread-safe & cross platform solution, I have adapted rmflow's approach into a similar interface. As this class modifies global file descriptors, I adapted it to a mutex-guarded static class that protects against multiple instances thrashing global file descriptors. In addition, rmflow's answer does not clean up all of the used file descriptors which can lead to problems opening new ones (for output streams or files) if many BeginCapture() & EndCapture() calls are used in one application. This code has been tested on Windows 7/8, Linux, OSX, Android, and iOS.
NOTE: In order to use std::mutex you must compile against c++ 11. If you do not / cannot use c++11, you can remove the mutex calls completely (sacrificing thread safety) or you can find a legacy sychronization mechanism to get the job done.
#ifdef _MSC_VER
#include <io.h>
#define popen _popen
#define pclose _pclose
#define stat _stat
#define dup _dup
#define dup2 _dup2
#define fileno _fileno
#define close _close
#define pipe _pipe
#define read _read
#define eof _eof
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <stdio.h>
#include <mutex>
class StdCapture
{
public:
static void Init()
{
// make stdout & stderr streams unbuffered
// so that we don't need to flush the streams
// before capture and after capture
// (fflush can cause a deadlock if the stream is currently being
std::lock_guard<std::mutex> lock(m_mutex);
setvbuf(stdout,NULL,_IONBF,0);
setvbuf(stderr,NULL,_IONBF,0);
}
static void BeginCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_capturing)
return;
secure_pipe(m_pipe);
m_oldStdOut = secure_dup(STD_OUT_FD);
m_oldStdErr = secure_dup(STD_ERR_FD);
secure_dup2(m_pipe[WRITE],STD_OUT_FD);
secure_dup2(m_pipe[WRITE],STD_ERR_FD);
m_capturing = true;
#ifndef _MSC_VER
secure_close(m_pipe[WRITE]);
#endif
}
static bool IsCapturing()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_capturing;
}
static bool EndCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_capturing)
return;
m_captured.clear();
secure_dup2(m_oldStdOut, STD_OUT_FD);
secure_dup2(m_oldStdErr, STD_ERR_FD);
const int bufSize = 1025;
char buf[bufSize];
int bytesRead = 0;
bool fd_blocked(false);
do
{
bytesRead = 0;
fd_blocked = false;
#ifdef _MSC_VER
if (!eof(m_pipe[READ]))
bytesRead = read(m_pipe[READ], buf, bufSize-1);
#else
bytesRead = read(m_pipe[READ], buf, bufSize-1);
#endif
if (bytesRead > 0)
{
buf[bytesRead] = 0;
m_captured += buf;
}
else if (bytesRead < 0)
{
fd_blocked = (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
while(fd_blocked || bytesRead == (bufSize-1));
secure_close(m_oldStdOut);
secure_close(m_oldStdErr);
secure_close(m_pipe[READ]);
#ifdef _MSC_VER
secure_close(m_pipe[WRITE]);
#endif
m_capturing = false;
}
static std::string GetCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_captured;
}
private:
enum PIPES { READ, WRITE };
int StdCapture::secure_dup(int src)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = dup(src);
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
return ret;
}
void StdCapture::secure_pipe(int * pipes)
{
int ret = -1;
bool fd_blocked = false;
do
{
#ifdef _MSC_VER
ret = pipe(pipes, 65536, O_BINARY);
#else
ret = pipe(pipes) == -1;
#endif
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
}
void StdCapture::secure_dup2(int src, int dest)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = dup2(src,dest);
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
}
void StdCapture::secure_close(int & fd)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = close(fd);
fd_blocked = (errno == EINTR);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
fd = -1;
}
static int m_pipe[2];
static int m_oldStdOut;
static int m_oldStdErr;
static bool m_capturing;
static std::mutex m_mutex;
static std::string m_captured;
};
// actually define vars.
int StdCapture::m_pipe[2];
int StdCapture::m_oldStdOut;
int StdCapture::m_oldStdErr;
bool StdCapture::m_capturing;
std::mutex StdCapture::m_mutex;
std::string StdCapture::m_captured;
call Init() once (before capture) to remove buffering to stdout / stderr
call BeginCapture() when you need to start capture
call EndCapture() when you need to stop capture
call GetCapture() to retrieve captured output
call IsCapturing() to see if stdout/stderr is currently redirected
i've furnished a qt osx ready variation from Björn Pollex code
#include <stdio.h>
#include <iostream>
#include <streambuf>
#include <stdlib.h>
#include <string>
#include <sstream>
class CoutRedirect {
public:
CoutRedirect() {
old = std::cout.rdbuf( buffer.rdbuf() ); // redirect cout to buffer stream
}
std::string getString() {
return buffer.str(); // get string
}
~CoutRedirect( ) {
std::cout.rdbuf( old ); // reverse redirect
}
private:
std::stringstream buffer;
std::streambuf * old;
};
Since your question is tagged C as well as C++, it seems appropriate to mention that although you cannot associate a string to a FILE * in standard C, there are several non-standard libraries that allow that. glibc is almost standard, so you may be perfectly happy using fmemopen() See http://www.gnu.org/s/libc/manual/html_mono/libc.html#String-Streams
I modified class from Sir Digby Chicken Caesar so that it's not static and could be used easily in unit tests. It works for me on Windows compiled by gcc (g++), but I cannot guarantee that it is 100% correct, please leave comments if it is not.
Create object of class StdCapture, and just call BeginCapture() to begin capture and EndCapture() at the end. Code from Init() is moved to the constructor. There shall be only one such object working at a time.
StdCapture.h:
#ifdef _MSC_VER
#include <io.h>
#define popen _popen
#define pclose _pclose
#define stat _stat
#define dup _dup
#define dup2 _dup2
#define fileno _fileno
#define close _close
#define pipe _pipe
#define read _read
#define eof _eof
#else
#include <unistd.h>
#endif
#include <fcntl.h>
#include <stdio.h>
#include <mutex>
#include <chrono>
#include <thread>
#ifndef STD_OUT_FD
#define STD_OUT_FD (fileno(stdout))
#endif
#ifndef STD_ERR_FD
#define STD_ERR_FD (fileno(stderr))
#endif
class StdCapture
{
public:
StdCapture();
void BeginCapture();
bool IsCapturing();
bool EndCapture();
std::string GetCapture();
private:
enum PIPES { READ, WRITE };
int secure_dup(int src);
void secure_pipe(int * pipes);
void secure_dup2(int src, int dest);
void secure_close(int & fd);
int m_pipe[2];
int m_oldStdOut;
int m_oldStdErr;
bool m_capturing;
std::mutex m_mutex;
std::string m_captured;
};
StdCapture.cpp:
#include "StdCapture.h"
StdCapture::StdCapture():
m_capturing(false)
{
// make stdout & stderr streams unbuffered
// so that we don't need to flush the streams
// before capture and after capture
// (fflush can cause a deadlock if the stream is currently being
std::lock_guard<std::mutex> lock(m_mutex);
setvbuf(stdout,NULL,_IONBF,0);
setvbuf(stderr,NULL,_IONBF,0);
}
void StdCapture::BeginCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
if (m_capturing)
return;
secure_pipe(m_pipe);
m_oldStdOut = secure_dup(STD_OUT_FD);
m_oldStdErr = secure_dup(STD_ERR_FD);
secure_dup2(m_pipe[WRITE],STD_OUT_FD);
secure_dup2(m_pipe[WRITE],STD_ERR_FD);
m_capturing = true;
#ifndef _MSC_VER
secure_close(m_pipe[WRITE]);
#endif
}
bool StdCapture::IsCapturing()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_capturing;
}
bool StdCapture::EndCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
if (!m_capturing)
return true;
m_captured.clear();
secure_dup2(m_oldStdOut, STD_OUT_FD);
secure_dup2(m_oldStdErr, STD_ERR_FD);
const int bufSize = 1025;
char buf[bufSize];
int bytesRead = 0;
bool fd_blocked(false);
do
{
bytesRead = 0;
fd_blocked = false;
#ifdef _MSC_VER
if (!eof(m_pipe[READ]))
bytesRead = read(m_pipe[READ], buf, bufSize-1);
#else
bytesRead = read(m_pipe[READ], buf, bufSize-1);
#endif
if (bytesRead > 0)
{
buf[bytesRead] = 0;
m_captured += buf;
}
else if (bytesRead < 0)
{
fd_blocked = (errno == EAGAIN || errno == EWOULDBLOCK || errno == EINTR);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
}
while(fd_blocked || bytesRead == (bufSize-1));
secure_close(m_oldStdOut);
secure_close(m_oldStdErr);
secure_close(m_pipe[READ]);
#ifdef _MSC_VER
secure_close(m_pipe[WRITE]);
#endif
m_capturing = false;
return true;
}
std::string StdCapture::GetCapture()
{
std::lock_guard<std::mutex> lock(m_mutex);
return m_captured;
}
int StdCapture::secure_dup(int src)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = dup(src);
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
return ret;
}
void StdCapture::secure_pipe(int * pipes)
{
int ret = -1;
bool fd_blocked = false;
do
{
#ifdef _MSC_VER
ret = pipe(pipes, 65536, O_BINARY);
#else
ret = pipe(pipes) == -1;
#endif
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
}
void StdCapture::secure_dup2(int src, int dest)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = dup2(src,dest);
fd_blocked = (errno == EINTR || errno == EBUSY);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
}
void StdCapture::secure_close(int & fd)
{
int ret = -1;
bool fd_blocked = false;
do
{
ret = close(fd);
fd_blocked = (errno == EINTR);
if (fd_blocked)
std::this_thread::sleep_for(std::chrono::milliseconds(10));
}
while (ret < 0);
fd = -1;
}

Get path of executable

I know this question has been asked before but I still haven't seen a satisfactory answer, or a definitive "no, this cannot be done", so I'll ask again!
All I want to do is get the path to the currently running executable, either as an absolute path or relative to where the executable is invoked from, in a platform-independent fashion. I though boost::filesystem::initial_path was the answer to my troubles but that seems to only handle the 'platform-independent' part of the question - it still returns the path from which the application was invoked.
For a bit of background, this is a game using Ogre, which I'm trying to profile using Very Sleepy, which runs the target executable from its own directory, so of course on load the game finds no configuration files etc. and promptly crashes. I want to be able to pass it an absolute path to the configuration files, which I know will always live alongside the executable. The same goes for debugging in Visual Studio - I'd like to be able to run $(TargetPath) without having to set the working directory.
There is no cross platform way that I know.
For Linux: pass "/proc/self/exe" to std::filesystem::canonical or readlink.
Windows: pass NULL as the module handle to GetModuleFileName.
The boost::dll::program_location function is one of the best cross platform methods of getting the path of the running executable that I know of. The DLL library was added to Boost in version 1.61.0.
The following is my solution. I have tested it on Windows, Mac OS X, Solaris, Free BSD, and GNU/Linux.
It requires Boost 1.55.0 or greater. It uses the Boost.Filesystem library directly and the Boost.Locale library and Boost.System library indirectly.
src/executable_path.cpp
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
# include <boost/process.hpp>
#endif
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
# include <Windows.h>
#endif
#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>
namespace boost {
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector buf(1024, 0);
size_type size = buf.size();
bool havePath = false;
bool shouldContinue = true;
do
{
DWORD result = GetModuleFileNameA(nullptr, &buf[0], size);
DWORD lastError = GetLastError();
if (result == 0)
{
shouldContinue = false;
}
else if (result < size)
{
havePath = true;
shouldContinue = false;
}
else if (
result == size
&& (lastError == ERROR_INSUFFICIENT_BUFFER || lastError == ERROR_SUCCESS)
)
{
size *= 2;
buf.resize(size);
}
else
{
shouldContinue = false;
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
// On Microsoft Windows, there is no need to call boost::filesystem::canonical or
// boost::filesystem::path::make_preferred. The path returned by GetModuleFileNameA
// is the one we want.
std::string ret = &buf[0];
return ret;
}
#elif (BOOST_OS_MACOS)
# include <mach-o/dyld.h>
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
char_vector buf(1024, 0);
uint32_t size = static_cast<uint32_t>(buf.size());
bool havePath = false;
bool shouldContinue = true;
do
{
int result = _NSGetExecutablePath(&buf[0], &size);
if (result == -1)
{
buf.resize(size + 1);
std::fill(std::begin(buf), std::end(buf), 0);
}
else
{
shouldContinue = false;
if (buf.at(0) != 0)
{
havePath = true;
}
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#elif (BOOST_OS_SOLARIS)
# include <stdlib.h>
std::string executable_path(const char* argv0)
{
std::string ret = getexecname();
if (ret.empty())
{
return detail::executable_path_fallback(argv0);
}
boost::filesystem::path p(ret);
if (!p.has_root_directory())
{
boost::system::error_code ec;
p = boost::filesystem::canonical(
p, boost::filesystem::current_path(), ec);
if (ec.value() != boost::system::errc::success)
{
return detail::executable_path_fallback(argv0);
}
ret = p.make_preferred().string();
}
return ret;
}
#elif (BOOST_OS_BSD)
# include <sys/sysctl.h>
std::string executable_path(const char* argv0)
{
typedef std::vector<char> char_vector;
int mib[4]{0};
size_t size;
mib[0] = CTL_KERN;
mib[1] = KERN_PROC;
mib[2] = KERN_PROC_PATHNAME;
mib[3] = -1;
int result = sysctl(mib, 4, nullptr, &size, nullptr, 0);
if (-1 == result)
{
return detail::executable_path_fallback(argv0);
}
char_vector buf(size + 1, 0);
result = sysctl(mib, 4, &buf[0], &size, nullptr, 0);
if (-1 == result)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#elif (BOOST_OS_LINUX)
# include <unistd.h>
std::string executable_path(const char *argv0)
{
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector buf(1024, 0);
size_type size = buf.size();
bool havePath = false;
bool shouldContinue = true;
do
{
ssize_t result = readlink("/proc/self/exe", &buf[0], size);
if (result < 0)
{
shouldContinue = false;
}
else if (static_cast<size_type>(result) < size)
{
havePath = true;
shouldContinue = false;
size = result;
}
else
{
size *= 2;
buf.resize(size);
std::fill(std::begin(buf), std::end(buf), 0);
}
} while (shouldContinue);
if (!havePath)
{
return detail::executable_path_fallback(argv0);
}
std::string path(&buf[0], size);
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
path, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
return detail::executable_path_fallback(argv0);
}
#else
std::string executable_path(const char *argv0)
{
return detail::executable_path_fallback(argv0);
}
#endif
}
src/detail/executable_path_internals.cpp
#include <cstdio>
#include <cstdlib>
#include <algorithm>
#include <iterator>
#include <string>
#include <vector>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <boost/predef.h>
#include <boost/version.hpp>
#include <boost/tokenizer.hpp>
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
# include <boost/process.hpp>
#endif
#if (BOOST_OS_CYGWIN || BOOST_OS_WINDOWS)
# include <Windows.h>
#endif
#include <boost/executable_path.hpp>
#include <boost/detail/executable_path_internals.hpp>
namespace boost {
namespace detail {
std::string GetEnv(const std::string& varName)
{
if (varName.empty()) return "";
#if (BOOST_OS_BSD || BOOST_OS_CYGWIN || BOOST_OS_LINUX || BOOST_OS_MACOS || BOOST_OS_SOLARIS)
char* value = std::getenv(varName.c_str());
if (!value) return "";
return value;
#elif (BOOST_OS_WINDOWS)
typedef std::vector<char> char_vector;
typedef std::vector<char>::size_type size_type;
char_vector value(8192, 0);
size_type size = value.size();
bool haveValue = false;
bool shouldContinue = true;
do
{
DWORD result = GetEnvironmentVariableA(varName.c_str(), &value[0], size);
if (result == 0)
{
shouldContinue = false;
}
else if (result < size)
{
haveValue = true;
shouldContinue = false;
}
else
{
size *= 2;
value.resize(size);
}
} while (shouldContinue);
std::string ret;
if (haveValue)
{
ret = &value[0];
}
return ret;
#else
return "";
#endif
}
bool GetDirectoryListFromDelimitedString(
const std::string& str,
std::vector<std::string>& dirs)
{
typedef boost::char_separator<char> char_separator_type;
typedef boost::tokenizer<
boost::char_separator<char>, std::string::const_iterator,
std::string> tokenizer_type;
dirs.clear();
if (str.empty())
{
return false;
}
#if (BOOST_OS_WINDOWS)
const std::string os_pathsep(";");
#else
const std::string os_pathsep(":");
#endif
char_separator_type pathSep(os_pathsep.c_str());
tokenizer_type strTok(str, pathSep);
typename tokenizer_type::iterator strIt;
typename tokenizer_type::iterator strEndIt = strTok.end();
for (strIt = strTok.begin(); strIt != strEndIt; ++strIt)
{
dirs.push_back(*strIt);
}
if (dirs.empty())
{
return false;
}
return true;
}
std::string search_path(const std::string& file)
{
if (file.empty()) return "";
std::string ret;
#if (BOOST_VERSION > BOOST_VERSION_NUMBER(1,64,0))
{
namespace bp = boost::process;
boost::filesystem::path p = bp::search_path(file);
ret = p.make_preferred().string();
}
#endif
if (!ret.empty()) return ret;
// Drat! I have to do it the hard way.
std::string pathEnvVar = GetEnv("PATH");
if (pathEnvVar.empty()) return "";
std::vector<std::string> pathDirs;
bool getDirList = GetDirectoryListFromDelimitedString(pathEnvVar, pathDirs);
if (!getDirList) return "";
std::vector<std::string>::const_iterator it = pathDirs.cbegin();
std::vector<std::string>::const_iterator itEnd = pathDirs.cend();
for ( ; it != itEnd; ++it)
{
boost::filesystem::path p(*it);
p /= file;
if (boost::filesystem::exists(p) && boost::filesystem::is_regular_file(p))
{
return p.make_preferred().string();
}
}
return "";
}
std::string executable_path_fallback(const char *argv0)
{
if (argv0 == nullptr) return "";
if (argv0[0] == 0) return "";
#if (BOOST_OS_WINDOWS)
const std::string os_sep("\\");
#else
const std::string os_sep("/");
#endif
if (strstr(argv0, os_sep.c_str()) != nullptr)
{
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
argv0, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
return p.make_preferred().string();
}
}
std::string ret = search_path(argv0);
if (!ret.empty())
{
return ret;
}
boost::system::error_code ec;
boost::filesystem::path p(
boost::filesystem::canonical(
argv0, boost::filesystem::current_path(), ec));
if (ec.value() == boost::system::errc::success)
{
ret = p.make_preferred().string();
}
return ret;
}
}
}
include/boost/executable_path.hpp
#ifndef BOOST_EXECUTABLE_PATH_HPP_
#define BOOST_EXECUTABLE_PATH_HPP_
#pragma once
#include <string>
namespace boost {
std::string executable_path(const char * argv0);
}
#endif // BOOST_EXECUTABLE_PATH_HPP_
include/boost/detail/executable_path_internals.hpp
#ifndef BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
#define BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
#pragma once
#include <string>
#include <vector>
namespace boost {
namespace detail {
std::string GetEnv(const std::string& varName);
bool GetDirectoryListFromDelimitedString(
const std::string& str,
std::vector<std::string>& dirs);
std::string search_path(const std::string& file);
std::string executable_path_fallback(const char * argv0);
}
}
#endif // BOOST_DETAIL_EXECUTABLE_PATH_INTERNALS_HPP_
I have a complete project, including a test application and CMake build files available at SnKOpen - /cpp/executable_path/trunk. This version is more complete than the version I provided here. It is also supports more platforms.
I have tested the application on all supported operating systems in the following four scenarios.
Relative path, executable in current directory: i.e. ./executable_path_test
Relative path, executable in another directory: i.e. ./build/executable_path_test
Full path: i.e. /some/dir/executable_path_test
Executable in path, file name only: i.e. executable_path_test
In all four scenarios, both the executable_path and executable_path_fallback functions work and return the same results.
Notes
This is an updated answer to this question. I updated the answer to take into consideration user comments and suggestions. I also added a link to a project in my SVN Repository.
This way uses boost + argv. You mentioned this may not be cross platform because it may or may not include the executable name. Well the following code should work around that.
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc,char** argv)
{
fs::path full_path( fs::initial_path<fs::path>() );
full_path = fs::system_complete( fs::path( argv[0] ) );
std::cout << full_path << std::endl;
//Without file name
std::cout << full_path.stem() << std::endl;
//std::cout << fs::basename(full_path) << std::endl;
return 0;
}
The following code gets the current working directory which may do what you need
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <iostream>
namespace fs = boost::filesystem;
int main(int argc,char** argv)
{
//current working directory
fs::path full_path( fs::current_path<fs::path>() );
std::cout << full_path << std::endl;
std::cout << full_path.stem() << std::endl;
//std::cout << fs::basepath(full_path) << std::endl;
return 0;
}
Note
Just realized that basename() was deprecated so had to switch to .stem()
C++17, windows, unicode, using filesystem new api:
#include "..\Project.h"
#include <filesystem>
using namespace std;
using namespace filesystem;
int wmain(int argc, wchar_t** argv)
{
auto dir = weakly_canonical(path(argv[0])).parent_path();
printf("%S", dir.c_str());
return 0;
}
(Important: Use wmain with wchar_t** - don't mix main with wchar_t**. For cmake projects enable unicode using add_definitions(-DUNICODE -D_UNICODE)).
Suspect this solution should be portable, but don't know how unicode is implemented on other OS's.
weakly_canonical is needed only if you use as Output Directory upper folder references ('..') to simplify path. If you don't use it - remove it.
If you're operating from dynamic link library (.dll /.so), then you might not have argv, then you can consider following solution:
application.h:
#pragma once
//
// https://en.cppreference.com/w/User:D41D8CD98F/feature_testing_macros
//
#ifdef __cpp_lib_filesystem
#include <filesystem>
#else
#include <experimental/filesystem>
namespace std {
namespace filesystem = experimental::filesystem;
}
#endif
std::filesystem::path getexepath();
application.cpp:
#include "application.h"
#ifdef _WIN32
#include <windows.h> //GetModuleFileNameW
#else
#include <limits.h>
#include <unistd.h> //readlink
#endif
std::filesystem::path getexepath()
{
#ifdef _WIN32
wchar_t path[MAX_PATH] = { 0 };
GetModuleFileNameW(NULL, path, MAX_PATH);
return path;
#else
char result[PATH_MAX];
ssize_t count = readlink("/proc/self/exe", result, PATH_MAX);
return std::string(result, (count > 0) ? count : 0);
#endif
}
I'm not sure about Linux, but try this for Windows:
#include <windows.h>
#include <iostream>
using namespace std ;
int main()
{
char ownPth[MAX_PATH];
// When NULL is passed to GetModuleHandle, the handle of the exe itself is returned
HMODULE hModule = GetModuleHandle(NULL);
if (hModule != NULL)
{
// Use GetModuleFileName() with module handle to get the path
GetModuleFileName(hModule, ownPth, (sizeof(ownPth)));
cout << ownPth << endl ;
system("PAUSE");
return 0;
}
else
{
cout << "Module handle is NULL" << endl ;
system("PAUSE");
return 0;
}
}
This is what I ended up with
The header file looks like this:
#pragma once
#include <string>
namespace MyPaths {
std::string getExecutablePath();
std::string getExecutableDir();
std::string mergePaths(std::string pathA, std::string pathB);
bool checkIfFileExists (const std::string& filePath);
}
Implementation
#if defined(_WIN32)
#include <windows.h>
#include <Shlwapi.h>
#include <io.h>
#define access _access_s
#endif
#ifdef __APPLE__
#include <libgen.h>
#include <limits.h>
#include <mach-o/dyld.h>
#include <unistd.h>
#endif
#ifdef __linux__
#include <limits.h>
#include <libgen.h>
#include <unistd.h>
#if defined(__sun)
#define PROC_SELF_EXE "/proc/self/path/a.out"
#else
#define PROC_SELF_EXE "/proc/self/exe"
#endif
#endif
namespace MyPaths {
#if defined(_WIN32)
std::string getExecutablePath() {
char rawPathName[MAX_PATH];
GetModuleFileNameA(NULL, rawPathName, MAX_PATH);
return std::string(rawPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char* exePath = new char[executablePath.length()];
strcpy(exePath, executablePath.c_str());
PathRemoveFileSpecA(exePath);
std::string directory = std::string(exePath);
delete[] exePath;
return directory;
}
std::string mergePaths(std::string pathA, std::string pathB) {
char combined[MAX_PATH];
PathCombineA(combined, pathA.c_str(), pathB.c_str());
std::string mergedPath(combined);
return mergedPath;
}
#endif
#ifdef __linux__
std::string getExecutablePath() {
char rawPathName[PATH_MAX];
realpath(PROC_SELF_EXE, rawPathName);
return std::string(rawPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char *executablePathStr = new char[executablePath.length() + 1];
strcpy(executablePathStr, executablePath.c_str());
char* executableDir = dirname(executablePathStr);
delete [] executablePathStr;
return std::string(executableDir);
}
std::string mergePaths(std::string pathA, std::string pathB) {
return pathA+"/"+pathB;
}
#endif
#ifdef __APPLE__
std::string getExecutablePath() {
char rawPathName[PATH_MAX];
char realPathName[PATH_MAX];
uint32_t rawPathSize = (uint32_t)sizeof(rawPathName);
if(!_NSGetExecutablePath(rawPathName, &rawPathSize)) {
realpath(rawPathName, realPathName);
}
return std::string(realPathName);
}
std::string getExecutableDir() {
std::string executablePath = getExecutablePath();
char *executablePathStr = new char[executablePath.length() + 1];
strcpy(executablePathStr, executablePath.c_str());
char* executableDir = dirname(executablePathStr);
delete [] executablePathStr;
return std::string(executableDir);
}
std::string mergePaths(std::string pathA, std::string pathB) {
return pathA+"/"+pathB;
}
#endif
bool checkIfFileExists (const std::string& filePath) {
return access( filePath.c_str(), 0 ) == 0;
}
}
For windows:
GetModuleFileName - returns the exe path + exe filename
To remove filename
PathRemoveFileSpec
QT provides this with OS abstraction as QCoreApplication::applicationDirPath()
If using C++17 one can do the following to get the path to the executable.
#include <filesystem>
std::filesystem::path getExecutablePath()
{
return std::filesystem::canonical("/proc/self/exe");
}
The above answer has been tested on Debian 10 using G++ 9.3.0
This is a Windows specific way, but it is at least half of your answer.
GetThisPath.h
/// dest is expected to be MAX_PATH in length.
/// returns dest
/// TCHAR dest[MAX_PATH];
/// GetThisPath(dest, MAX_PATH);
TCHAR* GetThisPath(TCHAR* dest, size_t destSize);
GetThisPath.cpp
#include <Shlwapi.h>
#pragma comment(lib, "shlwapi.lib")
TCHAR* GetThisPath(TCHAR* dest, size_t destSize)
{
if (!dest) return NULL;
if (MAX_PATH > destSize) return NULL;
DWORD length = GetModuleFileName( NULL, dest, destSize );
PathRemoveFileSpec(dest);
return dest;
}
mainProgram.cpp
TCHAR dest[MAX_PATH];
GetThisPath(dest, MAX_PATH);
I would suggest using platform detection as preprocessor directives to change the implementation of a wrapper function that calls GetThisPath for each platform.
Using args[0] and looking for '/' (or '\\'):
#include <string>
#include <iostream> // to show the result
int main( int numArgs, char *args[])
{
// Get the last position of '/'
std::string aux(args[0]);
// get '/' or '\\' depending on unix/mac or windows.
#if defined(_WIN32) || defined(WIN32)
int pos = aux.rfind('\\');
#else
int pos = aux.rfind('/');
#endif
// Get the path and the name
std::string path = aux.substr(0,pos+1);
std::string name = aux.substr(pos+1);
// show results
std::cout << "Path: " << path << std::endl;
std::cout << "Name: " << name << std::endl;
}
EDITED:
If '/' does not exist, pos==-1 so the result is correct.
For Windows you can use GetModuleFilename().
For Linux see BinReloc (old, defunct URL) mirror of BinReloc in datenwolf's GitHub repositories.
This is probably the most natural way to do it, while covering most major desktop platforms. I am not certain, but I believe this should work with all the BSD's, not just FreeBSD, if you change the platform macro check to cover all of them. If I ever get around to installing Solaris, I'll be sure to add that platform to the supported list.
Features full UTF-8 support on Windows, which not everyone cares enough to go that far.
procinfo/win32/procinfo.cpp
#ifdef _WIN32
#include "../procinfo.h"
#include <windows.h>
#include <tlhelp32.h>
#include <cstddef>
#include <vector>
#include <cwchar>
using std::string;
using std::wstring;
using std::vector;
using std::size_t;
static inline string narrow(wstring wstr) {
int nbytes = WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), NULL, 0, NULL, NULL);
vector<char> buf(nbytes);
return string{ buf.data(), (size_t)WideCharToMultiByte(CP_UTF8, 0, wstr.c_str(), (int)wstr.length(), buf.data(), nbytes, NULL, NULL) };
}
process_t ppid_from_pid(process_t pid) {
process_t ppid;
HANDLE hp = CreateToolhelp32Snapshot(TH32CS_SNAPPROCESS, 0);
PROCESSENTRY32 pe = { 0 };
pe.dwSize = sizeof(PROCESSENTRY32);
if (Process32First(hp, &pe)) {
do {
if (pe.th32ProcessID == pid) {
ppid = pe.th32ParentProcessID;
break;
}
} while (Process32Next(hp, &pe));
}
CloseHandle(hp);
return ppid;
}
string path_from_pid(process_t pid) {
string path;
HANDLE hm = CreateToolhelp32Snapshot(TH32CS_SNAPMODULE, pid);
MODULEENTRY32W me = { 0 };
me.dwSize = sizeof(MODULEENTRY32W);
if (Module32FirstW(hm, &me)) {
do {
if (me.th32ProcessID == pid) {
path = narrow(me.szExePath);
break;
}
} while (Module32NextW(hm, &me));
}
CloseHandle(hm);
return path;
}
#endif
procinfo/macosx/procinfo.cpp
#if defined(__APPLE__) && defined(__MACH__)
#include "../procinfo.h"
#include <libproc.h>
using std::string;
string path_from_pid(process_t pid) {
string path;
char buffer[PROC_PIDPATHINFO_MAXSIZE];
if (proc_pidpath(pid, buffer, sizeof(buffer)) > 0) {
path = string(buffer) + "\0";
}
return path;
}
#endif
procinfo/linux/procinfo.cpp
#ifdef __linux__
#include "../procinfo.h"
#include <cstdlib>
using std::string;
using std::to_string;
string path_from_pid(process_t pid) {
string path;
string link = string("/proc/") + to_string(pid) + string("/exe");
char *buffer = realpath(link.c_str(), NULL);
path = buffer ? : "";
free(buffer);
return path;
}
#endif
procinfo/freebsd/procinfo.cpp
#ifdef __FreeBSD__
#include "../procinfo.h"
#include <sys/sysctl.h>
#include <cstddef>
using std::string;
using std::size_t;
string path_from_pid(process_t pid) {
string path;
size_t length;
// CTL_KERN::KERN_PROC::KERN_PROC_PATHNAME(pid)
int mib[4] = { CTL_KERN, KERN_PROC, KERN_PROC_PATHNAME, pid };
if (sysctl(mib, 4, NULL, &length, NULL, 0) == 0) {
path.resize(length, '\0');
char *buffer = path.data();
if (sysctl(mib, 4, buffer, &length, NULL, 0) == 0) {
path = string(buffer) + "\0";
}
}
return path;
}
#endif
procinfo/procinfo.cpp
#include "procinfo.h"
#ifdef _WiN32
#include <process.h>
#endif
#include <unistd.h>
#include <cstddef>
using std::string;
using std::size_t;
process_t pid_from_self() {
#ifdef _WIN32
return _getpid();
#else
return getpid();
#endif
}
process_t ppid_from_self() {
#ifdef _WIN32
return ppid_from_pid(pid_from_self());
#else
return getppid();
#endif
}
string dir_from_pid(process_t pid) {
string fname = path_from_pid(pid);
size_t fp = fname.find_last_of("/\\");
return fname.substr(0, fp + 1);
}
string name_from_pid(process_t pid) {
string fname = path_from_pid(pid);
size_t fp = fname.find_last_of("/\\");
return fname.substr(fp + 1);
}
procinfo/procinfo.h
#ifdef _WiN32
#include <windows.h>
typedef DWORD process_t;
#else
#include <sys/types.h>
typedef pid_t process_t;
#endif
#include <string>
/* windows-only helper function */
process_t ppid_from_pid(process_t pid);
/* get current process process id */
process_t pid_from_self();
/* get parent process process id */
process_t ppid_from_self();
/* std::string possible_result = "C:\\path\\to\\file.exe"; */
std::string path_from_pid(process_t pid);
/* std::string possible_result = "C:\\path\\to\\"; */
std::string dir_from_pid(process_t pid);
/* std::string possible_result = "file.exe"; */
std::string name_from_pid(process_t pid);
This allows getting the full path to the executable of pretty much any process id, except on Windows there are some process's with security attributes which simply will not allow it, so wysiwyg, this solution is not perfect.
To address what the question was asking more precisely, you may do this:
procinfo.cpp
#include "procinfo/procinfo.h"
#include <iostream>
using std::string;
using std::cout;
using std::endl;
int main() {
cout << dir_from_pid(pid_from_self()) << endl;
return 0;
}
Build the above file structure with this command:
procinfo.sh
cd "${0%/*}"
g++ procinfo.cpp procinfo/procinfo.cpp procinfo/win32/procinfo.cpp procinfo/macosx/procinfo.cpp procinfo/linux/procinfo.cpp procinfo/freebsd/procinfo.cpp -o procinfo.exe
For downloading a copy of the files listed above:
git clone git://github.com/time-killer-games/procinfo.git
For more cross-platform process-related goodness:
https://github.com/time-killer-games/enigma-dev
See the readme for a list of most of the functions included.
As others mentioned, argv[0] is quite a nice solution, provided that the platform actually passes the executable path, which is surely not less probable than the OS being Windows (where WinAPI can help find the executable path). If you want to strip the string to only include the path to the directory where the executable resides, then using that path to find other application files (like game assets if your program is a game) is perfectly fine, since opening files is relative to the working directory, or, if provided, the root.
The following works as a quick and dirty solution, but note that it is far from being foolproof:
#include <iostream>
using namespace std ;
int main( int argc, char** argv)
{
cout << argv[0] << endl ;
return 0;
}
In case you need to handle unicode paths for Windows:
#include <Windows.h>
#include <iostream>
int wmain(int argc, wchar_t * argv[])
{
HMODULE this_process_handle = GetModuleHandle(NULL);
wchar_t this_process_path[MAX_PATH];
GetModuleFileNameW(NULL, this_process_path, sizeof(this_process_path));
std::wcout << "Unicode path of this app: " << this_process_path << std::endl;
return 0;
}
There are several answers recommending using GetModuleFileName on Windows. These answers have some shortcomings like:
The code should work for both UNICODE and ANSI versions
The path can be longer than MAX_PATH
GetModuleFileName function can fail and return 0
GetModuleFileName can return a relative executable name instead of a full name
GetModuleFileName can return a short path like C:\GIT-RE~1\TEST_G~1\test.exe
Let me provide an improved version, which takes into account the abovementioned points:
#include <Windows.h>
#include <string>
#include <memory>
#include <iostream>
// Converts relative name like "..\test.exe" to its full form like "C:\project\test.exe".
std::basic_string<TCHAR> get_full_name(const TCHAR const* name)
{
// First we need to get a length of the full name string
const DWORD full_name_length{GetFullPathName(name, 0, NULL, NULL)};
if (full_name_length == 0) {
// GetFullPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// Now, when we know the length, we create a buffer with correct size and write the full name into it
std::unique_ptr<TCHAR[]> full_name_buffer{new TCHAR[full_name_length]};
const DWORD res = GetFullPathName(name, full_name_length, full_name_buffer.get(), NULL);
if (res == 0) {
// GetFullPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// The full name has been successfully written to the buffer.
return std::basic_string<TCHAR>(full_name_buffer.get());
}
// Resolves short path like "C:\GIT-RE~1\TEST_G~1\test.exe" into its long form like "C:\git-repository\test_project\test.exe"
std::basic_string<TCHAR> get_long_name(const TCHAR const* name)
{
// First we need to get a length of the long name string
const DWORD long_name_length{GetLongPathName(name, 0, NULL)};
if (long_name_length == 0) {
// GetLongPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// Now, when we know the length, we create a buffer with correct size and write the full name into it
std::unique_ptr<TCHAR[]> long_name_buffer{new TCHAR[long_name_length]};
const DWORD res = GetLongPathName(name, long_name_buffer.get(), long_name_length);
if (res == 0) {
// GetLongPathName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
// The long name has been successfully written to the buffer.
return std::basic_string<TCHAR>(long_name_buffer.get());
}
std::basic_string<TCHAR> get_current_executable_full_name()
{
DWORD path_buffer_size = MAX_PATH; // we start with MAX_PATH because it is most likely that
// the path doesn't exceeds 260 characters
std::unique_ptr<TCHAR[]> path_buffer{new TCHAR[path_buffer_size]};
while (true) {
const auto bytes_written = GetModuleFileName(
NULL, path_buffer.get(), path_buffer_size);
const auto last_error = GetLastError();
if (bytes_written == 0) {
// GetModuleFileName call failed. Maybe you want to throw an exception.
return std::basic_string<TCHAR>{};
}
if (last_error == ERROR_INSUFFICIENT_BUFFER) {
// There is not enough space in our buffer to fit the path.
// We need to increase the buffer and try again.
path_buffer_size *= 2;
path_buffer.reset(new TCHAR[path_buffer_size]);
continue;
}
// GetModuleFileName has successfully written the executable name to the buffer.
// Now we need to convert it to a full long name
std::basic_string<TCHAR> full_name = get_full_name(path_buffer.get());
return get_long_name(full_name.c_str());
}
}
// Example of how this function can be used
int main()
{
#ifdef UNICODE
// If you use UNICODE version of WinApi
std::wstring exe_file_full_name = get_current_executable_full_name();
std::wstring exe_folder_full_name = exe_file_full_name.substr(0, exe_file_full_name.find_last_of(L"\\"));
std::wcout << exe_file_full_name << "\n"; // prints: C:\test_project\x64\Debug\test_program.exe
std::wcout << exe_folder_full_name << "\n"; // prints: C:\test_project\x64\Debug
#else
// If you use ANSI version of WinApi
std::string exe_file_full_name = get_current_executable_full_name();
std::string exe_folder_full_name = exe_file_full_name.substr(0, exe_file_full_name.find_last_of("\\"));
std::cout << exe_file_full_name << "\n"; // prints: C:\test_project\x64\Debug\test_program.exe
std::cout << exe_folder_full_name << "\n"; // prints: C:\test_project\x64\Debug
#endif
}
For Windows, you have the problem of how to strip the executable from the result of GetModuleFileName(). The Windows API call PathRemoveFileSpec() that Nate used for that purpose in his answer changed between Windows 8 and its predecessors. So how to remain compatible with both and safe? Luckily, there's C++17 (or Boost, if you're using an older compiler). I do this:
#include <windows.h>
#include <string>
#include <filesystem>
namespace fs = std::experimental::filesystem;
// We could use fs::path as return type, but if you're not aware of
// std::experimental::filesystem, you probably handle filenames
// as strings anyway in the remainder of your code. I'm on Japanese
// Windows, so wide chars are a must.
std::wstring getDirectoryWithCurrentExecutable()
{
int size = 256;
std::vector<wchar_t> charBuffer;
// Let's be safe, and find the right buffer size programmatically.
do {
size *= 2;
charBuffer.resize(size);
// Resize until filename fits. GetModuleFileNameW returns the
// number of characters written to the buffer, so if the
// return value is smaller than the size of the buffer, it was
// large enough.
} while (GetModuleFileNameW(NULL, charBuffer.data(), size) == size);
// Typically: c:/program files (x86)/something/foo/bar/exe/files/win64/baz.exe
// (Note that windows supports forward and backward slashes as path
// separators, so you have to be careful when searching through a path
// manually.)
// Let's extract the interesting part:
fs::path path(charBuffer.data()); // Contains the full path including .exe
return path.remove_filename() // Extract the directory ...
.w_str(); // ... and convert to a string.
}
SDL2 (https://www.libsdl.org/) library has two functions implemented across a wide spectrum of platforms:
SDL_GetBasePath
SDL_GetPrefPath
So if you don't want to reinvent the wheel... sadly, it means including the entire library, although it's got a quite permissive license and one could also just copy the code. Besides, it provides a lot of other cross-platform functionality.
I didn't read if my solution is already posted but on linux and osx you can read the 0 argument in your main function like this:
int main(int argument_count, char **argument_list) {
std::string currentWorkingDirectoryPath(argument_list[currentWorkingDirectory]);
std::size_t pos = currentWorkingDirectoryPath.rfind("/"); // position of "live" in str
currentWorkingDirectoryPath = currentWorkingDirectoryPath.substr (0, pos);
In the first item of argument_list the name of the executable is integrated but removed by the code above.
Here my simple solution that works in both Windows and Linux, based on this solution and modified with this answer:
#include <string>
using namespace std;
#if defined(_WIN32)
#include <algorithm> // for transform() in get_exe_path()
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <Windows.h>
#elif defined(__linux__)
#include <unistd.h> // for getting path of executable
#endif // Windows/Linux
string replace(const string& s, const string& from, const string& to) {
string r = s;
int p = 0;
while((p=(int)r.find(from, p))!=string::npos) {
r.replace(p, from.length(), to);
p += (int)to.length();
}
return r;
}
string get_exe_path() { // returns path where executable is located
string path = "";
#if defined(_WIN32)
wchar_t wc[260] = {0};
GetModuleFileNameW(NULL, wc, 260);
wstring ws(wc);
transform(ws.begin(), ws.end(), back_inserter(path), [](wchar_t c) { return (char)c; });
path = replace(path, "\\", "/");
#elif defined(__linux__)
char c[260];
int length = (int)readlink("/proc/self/exe", c, 260);
path = string(c, length>0 ? length : 0);
#endif // Windows/Linux
return path.substr(0, path.rfind('/')+1);
}
This was my solution in Windows. It is called like this:
std::wstring sResult = GetPathOfEXE(64);
Where 64 is the minimum size you think the path will be. GetPathOfEXE calls itself recursively, doubling the size of the buffer each time until it gets a big enough buffer to get the whole path without truncation.
std::wstring GetPathOfEXE(DWORD dwSize)
{
WCHAR* pwcharFileNamePath;
DWORD dwLastError;
HRESULT hrError;
std::wstring wsResult;
DWORD dwCount;
pwcharFileNamePath = new WCHAR[dwSize];
dwCount = GetModuleFileNameW(
NULL,
pwcharFileNamePath,
dwSize
);
dwLastError = GetLastError();
if (ERROR_SUCCESS == dwLastError)
{
hrError = PathCchRemoveFileSpec(
pwcharFileNamePath,
dwCount
);
if (S_OK == hrError)
{
wsResult = pwcharFileNamePath;
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
return wsResult;
}
else if(S_FALSE == hrError)
{
wsResult = pwcharFileNamePath;
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
//there was nothing to truncate off the end of the path
//returning something better than nothing in this case for the user
return wsResult;
}
else
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
std::ostringstream oss;
oss << "could not get file name and path of executing process. error truncating file name off path. last error : " << hrError;
throw std::runtime_error(oss.str().c_str());
}
}
else if (ERROR_INSUFFICIENT_BUFFER == dwLastError)
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
return GetPathOfEXE(
dwSize * 2
);
}
else
{
if (pwcharFileNamePath)
{
delete pwcharFileNamePath;
}
std::ostringstream oss;
oss << "could not get file name and path of executing process. last error : " << dwLastError;
throw std::runtime_error(oss.str().c_str());
}
}
char exePath[512];
CString strexePath;
GetModuleFileName(NULL,exePath,512);
strexePath.Format("%s",exePath);
strexePath = strexePath.Mid(0,strexePath.ReverseFind('\\'));
in Unix(including Linux) try 'which', in Windows try 'where'.
#include <stdio.h>
#define _UNIX
int main(int argc, char** argv)
{
char cmd[128];
char buf[128];
FILE* fp = NULL;
#if defined(_UNIX)
sprintf(cmd, "which %s > my.path", argv[0]);
#else
sprintf(cmd, "where %s > my.path", argv[0]);
#endif
system(cmd);
fp = fopen("my.path", "r");
fgets(buf, sizeof(buf), fp);
fclose(fp);
printf("full path: %s\n", buf);
unlink("my.path");
return 0;
}
As of C++17:
Make sure you include std filesystem.
#include <filesystem>
and now you can do this.
std::filesystem::current_path().string()
boost filesystem became part of the standard lib.
if you can't find it try to look under:
std::experimental::filesystem