SoDaRadio-5.0.3-master:8901fb5
FindHome.cxx
Go to the documentation of this file.
1 /*
2  Copyright (c) 2014, Matthew H. Reilly (kb1vc)
3  All rights reserved.
4 
5  Redistribution and use in source and binary forms, with or without
6  modification, are permitted provided that the following conditions are
7  met:
8 
9  Redistributions of source code must retain the above copyright
10  notice, this list of conditions and the following disclaimer.
11  Redistributions in binary form must reproduce the above copyright
12  notice, this list of conditions and the following disclaimer in
13  the documentation and/or other materials provided with the
14  distribution.
15 
16  THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
17  "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
18  LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
19  A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
20  HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
21  SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
22  LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
23  DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
24  THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
25  (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
26  OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
27 */
28 
29 #include "FindHome.hxx"
30 extern "C" {
31 #include <libgen.h>
32 #include <unistd.h>
33 #ifdef __linux__
34 #include <linux/limits.h>
35 #endif
36 }
37 
38 #include <iostream>
39 #include <stdexcept>
40 
50 std::string findHome()
51 {
52 #ifdef __linux__
53  // This solution was suggested by an answer in
54  // http://stackoverflow.com/questions/7051844/how-to-find-the-full-path-of-the-c-linux-program-from-within
55  char execution_path[PATH_MAX + 1] = {0};
56  ssize_t st = readlink("/proc/self/exe", execution_path, PATH_MAX);
57  if(st < 0) {
58  // readlink got an error.... throw something
59  throw std::runtime_error("Couldn't open /proc/self/exe");
60  }
61  // now trim the end of the path off, we just want the directory
62  char * mydir = dirname(execution_path);
63  return std::string(mydir);
64 #elif __OSX__
65  // This code has not been tested.
66 #endif
67 }
68 
std::string findHome()
Find the directory in which the calling program resides.
Definition: FindHome.cxx:50